Validating file types by regular expression


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:


However this does not seem to be working... can anyone give me a little reg ex help?

4/19/2019 8:57:21 PM

Accepted Answer

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):


You can use a tool like Expresso to test your regular expressions.

12/17/2008 4:23:15 PM


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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow