Validating file types by regular expression
Solution 1
Your regex seems a bit too complex in my opinion. Also, remember that the dot is a special character meaning "any character". The following regex should work (note the escaped dots):
^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$
You can use a tool like Expresso to test your regular expressions.
Solution 2
^.+\.(?:(?:[dD][oO][cC][xX]?)|(?:[pP][dD][fF]))$
Will accept .doc, .docx, .pdf files having a filename of at least one character:
^ = beginning of string
.+ = at least one character (any character)
\. = dot ('.')
(?:pattern) = match the pattern without storing the match)
[dD] = any character in the set ('d' or 'D')
[xX]? = any character in the set or none
('x' may be missing so 'doc' or 'docx' are both accepted)
| = either the previous or the next pattern
$ = end of matched string
Warning! Without enclosing the whole chain of extensions in (?:), an extension like .docpdf would pass.
You can test regular expressions at http://www.regextester.com/
Solution 3
Are you just looking to verify that the file is of a given extension? You can simplify what you are trying to do with something like this:
(.*?)\.(jpg|gif|doc|pdf)$
Then, when you call IsMatch() make sure to pass RegexOptions.IgnoreCase as your second parameter. There is no reason to have to list out the variations for casing.
Edit: As Dario mentions, this is not going to work for the RegularExpressionValidator, as it does not support casing options.
Solution 4
You can embed case insensitity into the regular expression like so:
\.(?i:)(?:jpg|gif|doc|pdf)$
Solution 5
You can use this template for every file type:
ValidationExpression="^.+\.(([pP][dD][fF])|([jJ][pP][gG])|([pP][nN][gG])))$"
for ex: you can add ([rR][aA][rR]
) for Rar file type and etc ...
mmattax
Senior Software Developer & Devops @ Formstack BS Computer Science, Purdue University Twitter: mmattax
Updated on April 20, 2020Comments
-
mmattax about 4 years
I have a .NET webform that has a file upload control that is tied to a regular expression validator. This validator needs to validate that only certain filetypes should be allowed for upload (jpg,gif,doc,pdf)
The current regular expression that does this is:
^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF|.doc|.DOC|.pdf|.PDF)$
However this does not seem to be working... can anyone give me a little reg ex help?