Thursday, 1 March 2012

Validating file types of Doc / Docx / Pdf / Jpeg / Bmp / Gif / Png by regular expression

^.+\.(?:(?:[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
 Similarly you can validate any file type as the above,
For JPG / BMP / Gif :
(.*\.([Jj][Pp][Gg])|([Bb][Mm][Pp])|([Gg][Ii][Ff])|([Pp][Nn][Gg])$)
Validating For Email:-
^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|
  (([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$
Validating USA Phone No.
((\(\d{3}\) ?)|(\d{3}[-.]))?\d{3}[-.]\d{4}( ext\d{0,}) 
it will accept as: 123.456.7890 
or
123-456-7890 or 123.456-7890(1 hyphen and 1 dot)
You can test it here: http://www.regextester.com/ 
 You can embed case insensitity into the regular expression like so: 
 \.(?i:)(?:jpg|gif|doc|pdf)$

No comments:

Post a Comment