File validation with jQuery and HTML5

I have been dealing with file uploads a lot recently, and I stumbled upon a few different methods for validating files which provide both basic file-type checking and file size checking before uploading.

The web app was already making use of jQuery with the excellent jQuery validation plugin; so I wrote a couple of extended validators.

File type validation (via file extension)

This defines an regular expression of valid file extensions, which we currently define as gif, jpeg/jpg and png.

This form of validation is quite widely supported; the file input exposes a file path (sometimes a fake path) along with the filename of the original file.

 * Basic file type validation support for common web-safe image formats.
 * @date  2011-09-22
 * @author  Michael Oldroyd
 * @version 1.0
    function(value, element) {
     if ($(element).attr('type') == "file"
     && ($(element).hasClass('required')
     ||  $(element).get(0).value.length > 0))
      return value.match(/\.([png|gif|jpg|jpeg])$/i);
      return true;
    "Invalid file type. Only PNG, JPEG and GIF formats are supported"

Leave a comment