z-file-validator
This module was written to handle client-side file input validation, using the File API.
Note: the plugin itself doesn't check for File API support, so the examples will assume that you have something under your belt to handle that. (Like Modernizr.)
Also: this module was written with jQuery in mind. This dependency will most likely be dropped in the future since hardly anything is used from jQuery's functionality.
Since this is a CommonJS module, it must be used alongside with Browserify, or something similar, like WebPacker.
Example, explanation
<!-- For convenience, sizes can be given as byte integers, or as numbers suffixed with one of the following: "Mb", "M", "Kb", "K". (Separating the numbers and the suffixes is also allowed, so "1024 K" will work just fine.) After the module loads the configuration, these will automatically be converted to byte integers. (In the example below, "5M" will be converted to 5242880)--><!-- Providing the configuration through a data-* attribute is optional. (Explained later in detail.)--> <!-- Exmplanation for the configuration options: - collective: These validations are running considering all the selected files. - "size" and "accept": These validations run for each selected file individually. - the "accept" attribute: this could also be provided by the JSON configuration, but as an attribute, most browsers will render the browsing window so that the selectable files are already filtered. Still, it can be used for testing purposes.-->
var FileValidator = ; // Suppose we have Modernizrif Modernizrfilereader // Saving the jQuery object for later use. var $input = ; // Initializing a FileValidator for the input var validator = $input 'configuration'; // Where // $input - The DOM input element selected by jQuery. // 'configuration' - The data- attribute's name. Now it expects a // `data-configuration` attribute to contain a valid // JSON configuration. // This could also be an object instead, in which case // there's no need for the data-* attribute. // By default, if the `validator.validate()` returns an error, the validator // also resets the file input. If you want to keep the selected value // regardless of the validation result, then just use the following: // `validator.setInputResetOnError(false);` // before running the validation. // Validate the input on change $input;
Validation error codes
Collective
- "collective.big_filesize"
- "collective.small_filesize"
- "collective.too_few_file"
- "collective.too_much_file"
Individual
- "big_filesize"
- "small_filesize"
- "bad_file_type"
Advanced usage
Most of the FileValidator methods can be used individually, if needed.
For example: with the validateFile
method, it's possible to validate only a
specific File:
var FileValidator = ; var validationResponse = FileValidatorprototype; console;// -> ["big_filesize"] or// -> true