Search This Blog

Google Analytics

Tuesday, July 13, 2010

File Upload Regular Expression not working on Firefox, Chrome and Safari

Ever tried using regular expressions to validate file upload extension when doing web development and ended up finding it to work on Microsoft Internet Explorer but not on Mozilla Firefox, Google Chrome and Apple Safari?

Scenario: Allow only files of extensions jpg, gif, png and bmp.

The first code snippet I am presenting is valid but will only work on Microsoft Internet Explorer.
^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF|.png|.PNG|.bmp|.BMP)$

This code snippet is better since it will work on all browsers, including Microsoft Internet Explorer, Mozilla Firefox, Google Chrome and Apple Safari.
(.*\.([gG][iI][fF]|[jJ][pP][gG]|[jJ][pP][eE][gG]|[bB][mM][pP]|[pP][nN][gG])$)

The first regular expression does not work other browsers other than Internet Explorer because the others do not allow JavaScript to get full absolute path name from the file input field. The first regular expression expects to a full path name.

The second regular expression works because it checks only the file name i.e. it does not expect a full absolute path name.

No comments:

Post a Comment

Do provide your constructive comment. I appreciate that.

Popular Posts