Validating FileUpload Control for Specific File Type and Required Field.
In this article I am going to explain how we can check and validate user for uploading only certain files and making uploading of file to be must for submission of form.
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.
Before starting about validating FileUpload we must have brief idea about FileUpload control and Validation Controls of ASP.Net
FileUpload control is used for uploading file to the server from the client side.
For detailed reading about FileUpload visit:
With this control, the validation fails if the input value does not change from its initial value. By default, the initial value is an empty string ("").
For more details visit: https://www.mindstick.com/Articles/195/requiredfieldvalidator-control-in-asp-dot-net
The RegularExpressionValidator control is used to ensure that an input value matches a specified pattern. The validation will not fail if the input control is empty. Use the RequiredFieldValidator control to make the field required.
For more details about RegularExpressionValidator visit following link:
Validating FileUpload Control in ASP.Net
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."
Here, regular expression for .doc, .docx, .txt files is:
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:
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>
The code above will validate FileUpload1 for required field.