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
 */
$.validator.addMethod(
    "image",
    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);
     else
      return true;
    },
    "Invalid file type. Only PNG, JPEG and GIF formats are supported"
);
http://www.michaeloldroyd.co.uk/2011/10/12/file-validation-with-jquery-and-html5/

Leave a comment