jQuery File Uploader JavaScript API: File Validation

We’ve built the next version of the File Uploader.

Validators allow restricting user choice to certain kinds of files. For example, you may want to only accept files less than 2MB in size or just PDF documents. With our API, a validator is a function that receives a fileInfo object for every uploaded file and throws an exception if that file does not meet your set requirements.

1function imagesOnly(fileInfo) {
2 if (fileInfo.isImage === false) {
3 throw new Error('image');
4 }
5}

Validators can be called once the info on file becomes available. All unknown fields used for validation have null values when a validator is called. This means a single validator can be called several times for a single file, each time testing if the required field is not null.

1function maxDimensions(width, height) {
2 return function(fileInfo) {
3 var imageInfo = fileInfo.originalImageInfo;
4 if (imageInfo !== null) {
5 if (imageInfo.width > width || imageInfo.height > height) {
6 throw new Error('dimensions');
7 }
8 }
9 };
10}

Validation inside jQuery File Uploader

Validators can also be added to the uploading widget through its validators property. This works for both single-file and multi-file widgets.

1var widget = uploadcare.Widget('#uploadcare-file');
2widget.validators.push(imagesOnly);

widget.validators is a regular javascript array. One uploading widget can be assigned several validators, and one validator can be assigned several widgets.

1firstWidget.validators.push(imagesOnly);
2secondWidget.validators.push(imagesOnly);
3firstWidget.validators.push(maxSize(1024 * 1024));
4firstWidget.validators.push(maxDimensions(800, 600));
5firstWidget.validators; // [function imagesOnly(){...}, function () {...}, function () {...}]

Note, you can’t rewrite validators with another object, you need to remove them from an original array.

1// Leave only first two validators:
2widget.validators = widget.validators.splice(0, 2); // WRONG!
3widget.validators.splice(2); // Correct.
4
5// Remove all validators:
6widget.validators = []; // WRONG!
7widget.validators.length = 0; // Correct.

Validation in JS API

You can add a validators array to a Settings object of any API function where it makes sense:

1uploadcare.openDialog(null, {
2 validators: [
3 imagesOnly,
4 maxSize(1024 * 1024),
5 minDimensions(800, 600)
6 ]
7});

The list of such functions includes but is not limited to: openDialog, openPanel, fileFrom, filesFrom, dragdrop.uploadDrop, dragdrop.receiveDrop.

It is better to use validators instead of checking file properties in widget.onChange and widget.onUploadComplete callbacks. Validators are activated before a dialog gets closed thus improving your UX.

Error messages

Each argument in the Error constructor is a key in your locale file. Such keys are mapped to messages shown to your users. The keys and messages can either be predefined like size, image, or custom.