13
$('#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 ?

6 Answers 6

21

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Binding on fileuploadprocessfail will do as well.
Thanks for this! Couldn't get validation/processing to work and was on the verge to write some crazy custom validations (as I've seen other people do). But it's as simple as including the appropriate required files.
18
+50

Here is what you want to do:

$('#fileupload')
    .fileupload({
        acceptFileTypes: /(\.|\/)(jpg)$/i
    })
    .bind('fileuploadadded', function (e, data) {
        console.log(data.files.valid);
    });

The core jquery.fileupload.js file is adding your files and triggering the "fileuploadadd" event, but that's before the files are validated.

The file jquery.fileupload-ui.js is doing the validation after the files are added, and triggering another "fileuploadadded" event once that's done.

Change the event, and you're all set.

Please Note:

This answer was valid and working as of March 2013 when it was posted. It appears that this upload plugin has changed since then. That means there is a new problem, and you should post a new question (or search to see if someone already has) rather than downvote this one!

4 Comments

Your fiddle is not working! And if I try to access data.files.valid in 'fileuploadadded' callback I get undefined...
The fiddle isn't working because the included js files are not available in the paths they are loaded from any more (404). This still doesn't work with the current version when set up correctly, but probably it once did.
It did work when I posted this answer. If it no longer works with the latest version of this plugin, then there is a new problem. Please post a new question, don't downvote this answer.
It returns undefined :(
2

This is what I did and it worked for me for newer versions: I created one validation per type of file and its size.

$("#fileUploadArea").fileupload({
        dataType: 'json',
        url:'${upload}',
        multiple:true,
        autoSubmit:false,
        maxNumberOfFiles: Number('${quantidadeMaximaArquivosUpload}'),
        dynamicFormData: function()
        {
            var data ={ 
                    idEntidadeEmpresarial: $('#idEntidadeEmpresarial').val(),
                    idDominioFamilia: $('#idDominioFamilia').val(),
                    idSubgrupo: $('select[id^="subgrupo_').map(function(){return $(this).val();}).get(),
                    descricao: $('#descricao').val(),
                    validade: $('#validade').val()
            }
            return data;
        },
        headers: {
            Accept: "application/json"
        },
        accept: 'application/json',        
        imageMaxWidth: 800,
        imageMaxHeight: 800,
        imageCrop: true ,
        stop: function(){
            $.unblockUI();
            if($('#fechar').is(":checked")){
                window.close();
            }else{
                $('select[id^="subgrupo_').each(function(){
                    $(this).val('');
                    $(this).trigger("chosen:updated");
                })
                $('#validade').val('');
                $('#descricao').val('');
                $('#sucesso').html('');
                $('#sucesso').append('<p><spring:message code="upload.sucesso"/>');
                $('#sucesso').show();
            }
        },
        error: function(files,status,errMsg)
        {
            $('#erro').html('');
            $('#erro').append('<p>'+errMsg+'</p>');
            $('#erro').show();
        },
        acceptFileTypes : ${listaExtensaoPermitidas}
    }).on('fileuploadprocessalways', function (e, data) {
        var currentFile = data.files[data.index];

        var tamanho = currentFile.size;
        var extensao = currentFile.name.substring(currentFile.name.lastIndexOf(".") +1,currentFile.name.length);            

        if(hashExtensao.get(extensao.toUpperCase()) < tamanho){
            alert("file type max size "+hashExtensao.get(extensao.toUpperCase());
            data.abort();
        }

    });

Comments

2

I think it can be possible using add method.

    var fileUploadInit = function() {
    $("#file-upload-form").fileupload({
        dataType: "json",
        url: url,
        add: function (e, data){
            if(validatefunction(data)){
                data.submit();
            } else {
                return false;
            }
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#upload-progress').css('width',progress + '%');
        },
        done: function(e, data) {
            debugger
        },
        processfail: function(e, data){
            debugger
        }

    })
}
var validatefunction = function(data){
    // Do validation here. Return true if everything is correct else return                 false
}

Comments

1

This is what you want to do with the newer version of the plugin (9.11.2): Include this files:
- jquery.ui.widget.js
- jquery.iframe-transport.js
- jquery.fileupload.js
- jquery.fileupload-process.js
- jquery.fileupload-validate.js

$('#fileupload')
.fileupload({
    acceptFileTypes: /(\.|\/)(jpg)$/i
})
.on('fileuploadadd', function (e, data) {
    console.log('validation object not available at this point. Do not do submit here');
})
.on('fileuploadprocessalways', function (e, data) {
    console.log(data.files.error);//true if error
    console.log(data.files[0].error);//error message
    if(!data.files.error) data.submit(); //do submission here
});

3 Comments

Not sure if there was another update since this comment was posted, but the latest version yet again (9.11.2) required a different method to implement validation: - Add the two files as mentioned before: 1) jquery.fileupload-process.js 2) jquery.fileupload-validate.js AFTER adding jquery.fileupload.js - add the validation config as processQueue eg: processQueue: [{ action: 'validate', acceptFileTypes: '..' }, { action: 'validate', maxFileSize: '..' }]
Sorry for the newest version. I have edited my post to clarify it.
Strangely enough, when I add processQueue, even with [] value, my resize is not triggering anymore... while validation starts working with this. I wnat both to work. :/
0

Well, the answer by @jszbody is the perfect answer.

However like myself in case if anyone lands here looking for solution to similar problem where user wants know if the file is not added correctly.

blueimp jquery-file-upload Doesn't throw error on unsuccessful add

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.