Showing posts with label File Upload Control. Show all posts
Showing posts with label File Upload Control. Show all posts

Saturday, 2 February 2013

Validating FileUpload control for specific file type and required field






Validating FileUpload control for specific file type and required field
For validating for required field we have to use RequiredFieldValidator and for validating for file types we’ll have to use RegularExpressionValidator. But, before starting we should have brief idea about the controls required.


Validating FileUpload Control in ASP.Net in C#

Validating File Upload Control certain file types. Here in the example below I am using RegularExpressionValidator to accomplish my task.

<asp:FileUpload ID="FileUpload1" runat="server" />  <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only .doc , .docx or .txt files are allowed."ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$"ControlToValidate="FileUpload1">*</asp:RegularExpressionValidator>


 Here, regular expression for .doc,  .docx,  .txt files is:

"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$"

If you want some more or other files type to be uploaded then you can replace or add more extension with the above mentioned extensions. Suppose you want your user to upload only .pdf file then you Regular expression for that will be:

"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.pdf)$"

But, this does not mean that user will be forced to upload file, this validation is only performed if user tries to upload file. If you want to make uploading of file mandatory then you have to use Required Field Validator.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="You have not uploaded your file" ControlToValidate="FileUpload1">* </asp:RequiredFieldValidator>

code which I had written on click of Upload button.