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?
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.
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.
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.
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.
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.
^.+\.(?:(?:[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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With