Validating browser upload file name and extension with simple regex
I got the regexp right. Works perfectly for Firefox ONLY. Ho开发者_如何学编程w 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.
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)$
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:
Extract the extension:
\.[a-zA-Z]{3,4}$
Lowercase the extension and validate it against an array of acceptable values.
Optionally validate the file's name (though I'd recommend cleaning it instead):
[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*
精彩评论