Uploading files, only to find that they are too large, or the wrong type is frustrating.
The fileValidator
plugin lets you warn users before they start uploading
enormous files.
Note: Some examples may not function properly when opened as a file (file://.../index.html).
Use fileValidator
to warn people when their uploaded files are too large or in the wrong format:
Basic usage is quite straightforward. Select the file inputs you wish to have validated, and invoke fileValidator
.
$( el ).fileValidator({ onValidation: function(files){ /* Called once before validating files */ }, onInvalid: function(validationType, file){ /* Called once for each invalid file */ }, maxSize: '2m', //optional type: 'image' //optional });
Validations may be specified either explicitly in the plugin's options, or implicitly with data attributes on the file input.
string
or number
The maximum size of the file. Units may by kilobytes, megabytes, or gigabytes. If no units are given, then bytes are assumed.
For example: "196kb"
, "5m"
, or "1.2g"
are all valid.
string
, regexp
, or function
The type of the file. If a string or a regular expression are passed in, then the mime type of the file must match. If a function is passed in, the function will be passed the mime type.
Each time a file input changes, the files are validated. All validations are called in the context of the element they were
bound to, so this
is the file input.
function(files)
Called before validating the list of files. This is a good point to do any setup you need before validating, for instance removing classes from a previous validation.
function(validationType, file)
This is called whenever a file fails its validation. The validationType
is the name of validation (eg: maxSize
).
This file
is the failing file.
Flag file fields with large documents:
$('input[type=file]').fileValidator({ onValidation: function(files){ $(this).attr('class',''); }, onInvalid: function(type, file){ $(this).addClass('invalid '+type); }, maxSize: '1m' });
Reject non image files:
$('input[type=file]').fileValidator({ onInvalid: function(type, file){ $(this).val(null); }, type: 'image' });
Instead of explicitly stating the validations, you can also encode them on the input fields:
<input type='file' name='small images' data-max-size='32k' data-type='image'/>
Not all browsers support the File API, specifically Internet Explorer users will not see validations. Also, you should never rely entirely on client side validations. Your server code should still validate any uploaded files.