In this article I will explain how to validate FileUpload Control using Regular Expression and RegularExpressionValidator in ASP.Net.
The validation will perform required validation and will also validate the selected file using File extension in ASP.Net.
Regular Expression
The following Regular Expression is used for validating the selected file in ASP.Net FileUpload control using its extension.
The Regular Expression can be modified to be used for multiple File extensions by simply adding and removing the extensions.
Note: The File Extensions must be separated by Pipe (|) character and must be prefixed with Dot (.) character.
Regular Expression for allowing Word Document and PDF files only
([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf)$
Regular Expression for allowing Image files only
([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.gif)$
Regular Expression for allowing Text files only
([a-zA-Z0-9\s_\\.\-:])+(.txt)$
Regular Expression for allowing Excel files only
([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$
Validating FileUpload Control using Regular Expression and RegularExpression Validator
The following HTML Markup consists of an ASP.Net FileUpload control, a Button and two Validators i.e. a RequiredField Validator and a RegularExpression Validator for validating extension of selected File.
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:RequiredFieldValidator ErrorMessage="Required" ControlToValidate="FileUpload1"
runat="server" Display="Dynamic" ForeColor="Red" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf)$"
ControlToValidate="FileUpload1" runat="server" ForeColor="Red" ErrorMessage="Please select a valid Word or PDF File file."
Display="Dynamic" />
<br />
<asp:Button Text="Submit" runat="server" />
Screenshot
Demo
Downloads