Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RegularExpression Validator for File Extension Validation in ASP.Net FileUpload

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading