Validate File Extension For Asp.net Fileupload Control On Client Side.

Here we will see how to validate a file extension for asp.net fileupload control on client side. Please also ensure that the extension is validate at server side as server side validation ensures that even if the javaScript client side checking fails still the file is validate at server side.

The code is as follows:

 <html xmlns="http://www.w3.org/1999/xhtml">  
 <head runat="server">  
   <title></title>  
   <script src="Scripts/jquery-1.7.1.js"></script>  
   <script>  
     function ValidateFileUploadExtension() {  
       var fupData = document.getElementById('<%= fileupload_resume.ClientID %>');  
       var FileUploadPath = fupData.value;  
       if (FileUploadPath == '') {  
         // There is no file selected  
         alert("Please select file to upload");  
         return false;  
       }  
       else {  
         var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();  
         if (Extension == "gif" || Extension == "jpeg" || Extension == "jpg" || Extension == "png" || Extension == "GIF" || Extension == "JPEG" || Extension == "JPG" || Extension == "PNG") {  
           return true;  
         }  
         else {  
           alert("Only '.jpeg','.jpg', '.png', '.gif', formats are allowed");  
           return false;  
         }  
       }  
     }  
   </script>  
 </head>  
 <body>  
   <form id="form1" runat="server">  
     <div>  
       Select the file you want to Upload.  
       <br />  
       <asp:FileUpload ID="fileupload_resume" runat="server" />  
       <br />  
       <asp:Button ID="Button1" runat="server" Text="Upload" OnClientClick="return ValidateFileUploadExtension();" />  
     </div>  
   </form>  
 </body>  
 </html>  

Leave a comment