c# – Validating file types by regular expression

c# – Validating file types by regular expression

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

n

^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$n

n

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

b’

^.+\.(?:(?:[dD][oO][cC][xX]?)|(?:[pP][dD][fF]))$n

n

Will accept .doc, .docx, .pdf files having a filename of at least one character:

n

^           = beginning of stringn.+          = at least one character (any character)n\.          = dot (.)n(?:pattern) = match the pattern without storing the match)n[dD]        = any character in the set (d or D)n[xX]?       = any character in the set or none n              (x may be missing so doc or docx are both accepted)n|           = either the previous or the next patternn$           = end of matched stringn

n

Warning! Without enclosing the whole chain of extensions in (?:), an extension like .docpdf would pass.

n

You can test regular expressions at http://www.regextester.com/

c# – Validating file types by regular expression

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:

n

(.*?)\.(jpg|gif|doc|pdf)$n

n

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.

n

Edit: As Dario mentions, this is not going to work for the RegularExpressionValidator, as it does not support casing options.

Leave a Reply

Your email address will not be published.