Home
 Index > ASP.NET Web Applications > How to create a CustomValidator for testing for...

ASP.NET Web Applications:  Validation

How to create a CustomValidator for testing for certain file types such as GIF or JPG Images

Shows how to create a custom validator that checks that an uploaded file is either a Jpeg or Gif with client-side and server-side validation.

Added on 17 Jul 2008

General Solutions:

Solution Summary:
The following code demonstrates how to perform validation on the FileUpload web control.
Solution Details:
JavaScript:

// Custom Validator takes two arguments, sender and args
function
 IconFileIsPic(sender, args) {
    
// use the client id of the file upload
    
var fuIcons = document.getElementById('ctl00_ContentPlaceHolder1_fvCategories_fuIcon'
);

    
// empty upload  control is valid
    
var
 isValid = (fuIcons.value.length = 0)
    
if
 (! isValid) {
         isValid = FileTypeValidator(fuIcons.value, [
'jpg''gif''jpeg'
])
     }
     args.IsValid = isValid;
}

// test for valid file types based on the file extension
function
 FileTypeValidator(fileName, fileTypes) {
    
if (!fileName) return
;

    arr = fileName.toLowerCase().split(
"."
)
    fileType = 
"."
 + arr[arr.length-1];
    
var
 valid;
    
if (fileTypes.join("."
).indexOf(fileType) != -1) {
        valid = 
true

    } 
else
 {
        valid = 
false
;
    }
    
return
 valid;
}

ASPX (FileUpload and CustomValidator Code only):

<!-- Add same ValidationGroup to ValidationSummary, UpdateButton and Validators -->
<asp:ValidationSummary ForeColor="Red" ValidationGroup="Category" 
                
ShowMessageBox="true" ShowSummary="false" ID="ValidationSummary1" 
                
runat="server" DisplayMode="List" />
<
asp:FileUpload ID="fuIcon" runat="Server" Visible="false" />
<
asp:CustomValidator ID="CustomValidator2" runat="server" 
               
Display="Dynamic" OnServerValidate="CheckImagType" ClientValidationFunction="IconFileIsPic" 
               
Text="*" ErrorMessage="File upload is not an acceptable image file. Jpegs and Gifs are the only allowable formats." 
               
ControlToValidate="fuIcon" ValidationGroup="Category"></asp:CustomValidator>
<
asp:Button ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" ValidationGroup="Category" />

ASPX.VB (Code-Behind):

    ' Check for the correct file extentions on the server-side
    Public Sub CheckImageType(ByVal source As ObjectByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
        
Dim fuIcon As FileUpload = CType(fvCategories.Row.FindControl("fuIcon"), FileUpload)
        
Dim isValid As Boolean = True
        If fuIcon.FileName.Length > 0 Then
            isValid = False
            Dim iconName As String = ""
            If fuIcon.Visible And fuIcon.HasFile Then
                Dim origName As String = fuIcon.FileName
                
Dim ext As String = origName.Substring(origName.LastIndexOf(".")).Replace(".""")
                
If ext.ToLower = "gif" Or ext.ToLower = "jpg" Or ext.ToLower = "jpeg" Then
                    isValid = True
                End If
            End If
        End If
        args.IsValid = isValid
    
End Sub

Was this solution useful? Yes No Added on 17 Jul 2008
Rating: 

Copyright 2012 © E-Centric, Inc. | Terms of Use