Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  ^(([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?

like image 689
mmattax Avatar asked Dec 17 '08 15:12

mmattax


People also ask

How do I verify a file type?

Right-click the file. Select the Properties option. In the Properties window, similar to what is shown below, see the Type of file entry, which is the file type and extension.

How do you validate a file type in JavaScript?

Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the allowed file types. For this we will use fileValidation() function. We will create fileValidation() function that contains the complete file type validation code.

Is RegEx used for validation?

You can use regular expressions to match and validate the text that users enter in cfinput and cftextinput tags. Ordinary characters are combined with special characters to define the match pattern. The validation succeeds only if the user input matches the pattern.

How do you validate a RegEx pattern?

RegEx pattern validation can be added to text input type questions. To add validation, click on the Validation icon on the text input type question.


2 Answers

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.

like image 88
Dario Solera Avatar answered Sep 29 '22 14:09

Dario Solera


^.+\.(?:(?:[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/

like image 37
mdunka Avatar answered Sep 29 '22 15:09

mdunka