0

I got the regexp right. Works perfectly for Firefox ONLY. How would i make this cross browser, cross platform manner. Since it is file name and extension validation you are right i am using File Upload control.

^[a-zA-Z0-9_\.]{3,28}(.pdf|.txt|.doc|.docx|.png|.gif|.jpeg|.jpg|.zip|.rar)$

matches File name must not be empty[ 3, 28 characters long].

Extension must be within the group.

When this works superb in forefox i assume because the fileUpload.value = Filename.extension in firefox. It awfully fails in Google chrome and IE. I am using the above with .net Regular Expression validator and ClientScript enabled.

I know how to validate it on server, so please no server side solutions.

note:

Google chrome:

Provides the fileupload control value as c:\fakePath\filename.extension

IE:

Provides the Full path.

1
  • please provide some examples of inputs you try to match and where exactly it fails Commented May 12, 2011 at 6:22

2 Answers 2

3

You can't use the ^ to start with if you sometimes have a full path but are only interested in the filename. The dot of the filending should be escaped.

You could try something like this:

[^\\/]{3,}\.(pdf|txt|doc|docx|png|gif|jpeg|jpg|zip|rar)$


As it looks you get only the file with Firefox but the full path with other browsers.
I'd always add a prefix / to your string and than validate the last part after the last fileseprator / or \.

This example uses lookahead to check the fileseparator (or manually added /) before the file and also allows the check of max 28 char for filename. see this online regex tester:

(?<=[\\/])[\w\.]{3,28}\.(?:pdf|txt|doc|docx|png|gif|jpeg|jpg|zip|rar)$
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the valuable explanation. this regex works across browsers now.
1

As things stand, your regex validates garbage like the following:

  • ....pdf
  • ____pdf

It also rejects perfectly valid files:

  • i.jpg
  • my-pic.jpg
  • pic.JPG

The easiest is to validate things in multiple steps:

  1. Extract the extension:

    \.[a-zA-Z]{3,4}$
    
  2. Lowercase the extension and validate it against an array of acceptable values.

  3. Optionally validate the file's name (though I'd recommend cleaning it instead):

    [a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.