Skip to content

Instantly share code, notes, and snippets.

@sanjayginde
Last active December 11, 2015 17:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanjayginde/4635275 to your computer and use it in GitHub Desktop.
Save sanjayginde/4635275 to your computer and use it in GitHub Desktop.
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.
/**
* 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'
});
/**
* 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."
}
});
/**
* Extension to Modernizer for File API support
*/
window.Modernizr.addTest('fileapi', function() { return window.File && window.FileReader; });
window.BYTES_PER_MEGABYTE = 1048576;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment