Jquery file upload plugin: how to validate files on add?

cetver picture cetver · Mar 21, 2013 · Viewed 46.6k times · Source
$('#fileupload')
    .fileupload({
        acceptFileTypes: /(\.|\/)(jpg)$/i
    })
    .on('fileuploadadd', function (e, data) {
        console.log(data.files.valid); //undefined
        setTimeout(function () {
            console.log(data.files.valid); //true or false
        }, 500);
    })
;

jsFiddle

How to get boolean value of property data.files.valid without timeout ?

Answer

bfncs picture bfncs · Nov 28, 2013

I needed to do validation with a current version of the plugin (5.39.1) and this works for me:

Be sure to include jquery.fileupload-process.js and jquery.fileupload-validate.js in this order after jquery.fileupload.js and before your initializing script.

In your initializing script add the validation options and check validation in the fileuploadprocessalways callback:

$('.fileinput').fileupload({
    // The regular expression for allowed file types, matches
    // against either file type or file name:
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    // The maximum allowed file size in bytes:
    maxFileSize: 10000000, // 10 MB
    // The minimum allowed file size in bytes:
    minFileSize: undefined, // No minimal file size
    // The limit of files to be uploaded:
    maxNumberOfFiles: 10
  }).on('fileuploadprocessalways', function (e, data) {
    var currentFile = data.files[data.index];
    if (data.files.error && currentFile.error) {
      // there was an error, do something about it
      console.log(currentFile.error);
    }
  });

All validations are optional, just don't leave the ones you don't need undefined.