Home > OS >  RegularExpression Validator for File Extension Validation in ASP.Net FileUpload
RegularExpression Validator for File Extension Validation in ASP.Net FileUpload

Time:06-10

I am trying to validate file upload file validation and seems this expression is not working.

  1. The file name can be only alphanumeric.
  2. No special characters.
  3. Allowed space.
  4. Extension can be .png|.jpg|.jpeg|.gif|.zip|.PNG|.JPG|.JPEG|.GIF|.ZIP

Tried below expression and both are not working.

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:RegularExpressionValidator 
   ValidationExpression="([a-zA-Z0-9\s_\\.\-:]) (.png|.jpg|.jpeg|.gif|.zip|.PNG|.JPG|.JPEG|.GIF|.ZIP)$"
    ControlToValidate="FileUpload1" runat="server" ErrorMessage="Please select a valid file." />
<asp:Button Text="Submit" runat="server" />

https://regex101.com/r/c6go4y/1

The expression validate this string 01 01.jpg with special character The string 01 01.jpg in my case it's wrong.

What am I doing wrong?

CodePudding user response:

Given your requirements for the regex expression I created this simplified version:

^([\w\s]) (.png|.jpg|.jpeg|.gif|.zip|.PNG|.JPG|.JPEG|.GIF|.ZIP)$
  • \w : matches all word characters including uppercase, lowercase and numerics. same as [a-zA-Z0-9_]
  • \s: matches white spaces

The extra matches that you have are unnecesary and also don't fullfill with your requirement of "no special characters"

demo: https://www.debuggex.com/r/hSDTsxmu0Jt6GRtA

CodePudding user response:

<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" />
  • Related