About the author

Vijay Kodali
E-mail me Send mail

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2024

Validate Asp.Net FileUpload control

Here is an example to validate Fileupload control. This validation will check user to upload files of particular type/extension.

Client side validation:

 

<asp:FileUpload ID="UploadFile" runat="server" />
<asp:Button Text="Save" ID="btnSave" runat="server" OnClientClick="javascript:return ValidateUpload();" />     
 <script type="text/javascript" language="javascript">
    function ValidateUpload()
            {           
                var Upload_file = document.getElementById('<%= UploadFile.ClientID %>');                
                var myfile = Upload_file.value;               
                if(myfile.indexOf("doc")>0)
                {
                 alert('Valid Format');
                }
                else
                {
                 alert('Invalid Format');
                }            
            }
 </script>
Validating with RegularExpression validator:
<asp:FileUpload ID="UploadFile" runat="server" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only Doc files are allowed" 
ControlToValidate="UploadFile" ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.DOC)$">
</asp:RegularExpressionValidator>

In this example, I checked  ".doc" file type but you can use this example for any file type. Just replace ".doc" with file type you would  like to check( "Xml", "wmv"...).


Categories: ASP.NET | ASP.Net 3.5
Posted by vijay on Thursday, October 16, 2008 8:26 PM
Permalink | Comments (3) | Post RSSRSS comment feed

Comments

Kevin United States

Tuesday, May 5, 2009 6:22 AM

Kevin

Hi Vijay, I was wondering if my file name is "document1.doc"  or "Clientdocuements.doc" so in that case, it might not work. What do you think?

Vijay

Tuesday, May 5, 2009 2:28 PM

Vijay

@Kevin, you are right regarding javascript validation. I will update that code in coming days. Thanks for that correction. Mean while RegularExpression validator code should work for you.

Murali India

Wednesday, August 29, 2012 3:59 AM

Murali

Use Below code Vijay. It'll work.

<script type="text/javascript" language="javascript">

    function ValidateUpload()

            {          

                var Upload_file = document.getElementById('<%= UploadFile.ClientID %>');                

                var myfile = Upload_file.value;              

                if(myfile.indexOf(".doc")>0)  

                {

                 alert('Valid Format');

                }

                else

                {

                 alert('Invalid Format');

                }            

            }

</script>

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading