Powered by Blogger.

Saturday, February 15, 2014

Regular expression validator for image files in Asp.Net




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

Also you can check out my previous posts on:

- What are different types of results in MVC?

- If Else statements in JavaScript Example

- Steps to create wcf service and host wcf service as windows service in C#.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.




0 comments

Post a Comment