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.
<!--For convenience, sizes can be given as byte integers, or as numbers suffixedwith one of the following: "Mb", "M", "Kb", "K".(Separating the numbers and the suffixes is also allowed, so "1024 K" willwork just fine.)After the module loads the configuration, these will automatically beconverted to byte integers. (In the example below, "5M" will be convertedto 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 theselected files.- "size" and "accept": These validations run for each selected fileindividually.- the "accept" attribute: this could also be provided by the JSONconfiguration, but as an attribute, most browsers will render thebrowsing 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 inputvar 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
Most of the FileValidator methods can be used individually, if needed.
For example: with the
validateFile method, it's possible to validate only a
var FileValidator = ;var validationResponse = FileValidatorprototype;console;// -> ["big_filesize"] or// -> true