mrojas
mrojas

Reputation: 85

How validate max number of files before upload?

Hi I'm using the upload file plugin and I need to validate the number of files added before upload the file...Something like this

        $('#fileupload').bind('fileuploadadd', function (e, data) {
        filestoupload++;
        var numOfDivs = $('.request').size();
        if (numOfDivs < filestoupload) {
            upload = false; // Is just an example.
        }
    });

Upvotes: 5

Views: 3162

Answers (2)

Gaddiel Sadoc Peralta
Gaddiel Sadoc Peralta

Reputation: 331

This worked for me, on your fileupload definition add a beforesend, and there do the validation

 var maxfiles=3;
 $('#fileupload').fileupload(({
    url: postFileUrl,
    submit: function (event, files) {
        //check for max files THIS IS WHERE YOU VALIDATE
        //console.log(files.originalFiles.length);
        var fileCount = files.originalFiles.length;
        if (fileCount > maxFiles) {
            alert("The max number of files is "+maxFiles);
            throw 'This is not an error. This is just to abort javascript';
            return false; 
        }
    }
  });

that throw is by far not elegant, if you happend to implement this and find a way to avoid that please make me know (for now is necesary or it will display the error alert for each file uploaded)

Upvotes: 1

berus97
berus97

Reputation: 384

use data.files.length

 $('#fileupload').bind('fileuploadsubmit', function (e, data) {
    var fileCount = data.files.length;
    if (fileCount < filestoupload) {
        upload = false; 
    }
});

Upvotes: 1

Related Questions