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
Control: 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:
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.
, .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.
ErrorMessage="You have not uploaded your file"
The code above will validate FileUpload1 for required field.