Click here to Skip to main content
15,890,670 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I want to validate file-upload control to allow only word document.
How can i achieve this?can any one tell.

I am using regular expression
HTML
^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$
but it will accept other files also.

can any one tell me?
Posted
Updated 20-Nov-11 20:45pm
v2
Comments
srinivas vadepally 19-Nov-11 7:08am    
Hi Thendral,
Better go with code behind.
or go through url
http://stackoverflow.com/questions/71944/how-do-i-validate-the-file-type-of-a-file-upload
srinivas vadepally 19-Nov-11 7:10am    
Have you provide the control to validate property?
Just verify it.

Hi,

You can't validate file on File Open Dialog in Asp.Net but you can validate file after selecting file from dialog.
Following are code to verify uploaded file is valid or not.

Javscript
JavaScript
<script type="text/javascript" language="javascript">
function validate() {
  var uploadcontrol = document.getElementById('<%=FileUpload1.ClientID%>').value;
  //Regular Expression for fileupload control.
  var reg = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.DOC|.DOCX)$/;
  if (uploadcontrol.length > 0)
  {
    //Checks with the control value.
    if (reg.test(uploadcontrol))
    {
       return true;
    }
    else
    {
       //If the condition not satisfied shows error message.
       alert("Only .doc, docx files are allowed!");
       return false;
    }
  }
} //End of function validate.
</script>



HTML
XML
<asp:fileupload id="FileUpload1" runat="server" xmlns:asp="#unknown" />
<asp:button id="Button1" runat="server" text="Button" onclientclick="return validate();" xmlns:asp="#unknown" />


VB
Thanks,
Imdadhusen
 
Share this answer
 
v2
Try this code behind
C#
string strextention = FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf('.'));
           if (strextention.ToLower() != ".doc")
            {
              //apply your logic here when not a doc file
            }
 
Share this answer
 
Comments
Sunasara Imdadhusen 21-Nov-11 5:02am    
But this will make overload to server because it will execute on server side. so it would be better if you can prevent from client side.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900