sanjayginde
1/25/2013 - 3:31 PM

JavaScript file size validation for HTML 5, using jQuery Tools validation and Parsley validation. (Additionally, extended modernizer for HTM

JavaScript file size validation for HTML 5, using jQuery Tools validation and Parsley validation. (Additionally, extended modernizer for HTML5 File API.). The 'data-filemaxsize' attribute should be set in megabytes.

/**
 * Extension to Modernizer for File API support
 */
window.Modernizr.addTest('fileapi', function() { return window.File && window.FileReader; });

window.BYTES_PER_MEGABYTE = 1048576;
/**
 * File size validation using Parsley JS Validation (http://parsleyjs.org)
 */
$('form').parsley({
  validators: {
    filemaxsize: function (val, max_megabytes, parsleyField) {
      if (!Modernizr.fileapi) { return true; }

      var $file_input = $(parsleyField.element);
      if ($file_input.is(':not(input[type="file"])')) {
        console.log("Validation on max file size only works on file input types");
        return true;
      }

      var max_bytes = max_megabytes * BYTES_PER_MEGABYTE, files = $file_input.get(0).files;

      if (files.length == 0) {
        // No file, so valid. (Required check should ensure file is selected)
        return true; 
      }

      return files.length == 1  && files[0].size <= max_bytes;
    }
  },
  messages: {
    filemaxsize: "The file cannot be more than %s megabytes."
  }
});
/**
 * File size validation using jQuery Tools Validation (http://jquerytools.org/documentation/validator/index.html)
 */
if (Modernizr.fileapi) {
  $.tools.validator.fn('input[type="file"][data-filemaxsize]', function($file_input, value) {
    var files = $file_input.get(0).files, 
        max_megabytes = parseInt($file_input.data('filemaxsize')),
        max_bytes = max_megabytes * BYTES_PER_MEGABYTE;

    if (files.length > 0 && files[0].size > max_bytes) {
      return "The selected file can not be larger than " + max_megabytes + " megabytes"
    }

    return true;
  });
}


$('form').validator({ 
  // Need to listen for 'change' event so error will disappear when user selects a file with a valid size.
  errorInputEvent: 'keyup change'
});