20 November 2013

Regular expression validator to validate image files in Asp.net

Here we will discuss how we can use regular expression validator to validate image files in Asp.net.

By using regular expression you can check wether a user is trying to upload a valid image file or not. Here we have taken a file upload control, a regular expression validator and a button.

The valid regular expression is: "^.*\.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(g|G))$"

Below is the full code:

<div>
            <asp:FileUpload ID="FileUpload1" runat="server" Width="449px" /><br />
            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
                ErrorMessage="Please enter a valid image file" ControlToValidate="FileUpload1" ForeColor="#FF3300"
                ValidationExpression="^.*\.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(g|G))$"></asp:RegularExpressionValidator>
            <br />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" />
 </div>

Here check the figure below, in the below fig i tried to upload an docx file and it is showing me the validation message.



And the below fig I am trying to upload a png file and no validation message is showing.




No comments:

Post a Comment