5

I would like to ask how to validate multiple file input using the jQuery validation-plugin.

Currently I have these codes but it doesn't work:

.html:

<form id="uploadPhotoForm" enctype="multipart/form-data" method="POST">
    <table class= "uploadPhotoTable">
        <tr>
            <td>Photo</td>
            <td>:</td>
            <td><input class="field" type="file" name="files[]" id="upload_photo" align='right' multiple /></td>
        </tr>
    </table>    
</form>

.js:

$('#uploadPhotoForm').validate({
    rules: {
      files: {
      required: true,
      extension: "png"
    }
    },
    messages:{
        files:{
           required : "Please upload atleast 1 photo",
           extension:"Only png file is allowed!"
        }       
    }
  });

I also will use this code to post to new PHP for processing. But it seems like in my uploadPhoto.php, $_FILES['files']['tmp_name'] is undefined. May i know how to solve this?

if ($('#uploadPhotoForm').valid()) {       
    $.ajax({
        url: "inc/uploadPhoto.php",
        type: "POST",
        data:  new FormData(this),
        contentType: false,
        cache: false,
        processData:false,
        success: function(data){
           $("#error1").html(data);
        }           
    });
}

2 Answers 2

5

You need to 'files[]' instead of files, and if you doesn't add additional-methods.js, you will do it.

  $('#uploadPhotoForm').validate({
    rules: {
      'files[]': {
      required: true,
      extension: "png"
    }
    },
    messages:{
        'files[]':{
           required : "Please upload atleast 1 photo",
           extension:"Only png file is allowed!"
        }

    }

See jsFiddle.

About serialize. Please read this how to do file upload using jquery serialization

Update:

It will work

if ($('#uploadPhotoForm').valid()) {  
    var form = $('#uploadPhotoForm')[0]; //  [0], because you need to use standart javascript object here
    var formData = new FormData(form);
    $.ajax({
        url: "inc/uploadPhoto.php",
        type: "POST",
        data:  formData,
        contentType: false,
        cache: false,
        processData:false,
        success: function(data){
           $("#error1").html(data);
        }           
    });
}

Your code haven't work i think because this in data: new FormData(this), not valid javascript form object.

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

4 Comments

thanks for ur ans... i have another question to ask regarding this.. usually i will use this code to post to new php for processing, but it seems like in my uploadPhoto.php, $_FILES['files']['tmp_name'] is undefined..may i know how to solve this? $.post('inc/uploadPhoto.php', $("#uploadPhotoForm").serialize(), function(data) {});
I added link in my answer.
it seems like it doesnt work for me... can u show me an example?
Select two files. One png and other pdf. It will not show validation message.
2

For some one who might land on this page through google.I solved it using the following solution since it was not working properly with multiple uploads with different formats.

<input type="file" id="upload_files" name="uploaded_files[]"  required="required" multiple>

I made a custom validator method since the default validator was not validating multiple files properly.If I select 1st file as pdf and other one png.This example validates pdf,doc and docx files.

$(function() {
    $.validator.addMethod(
            "validate_file_type",
            function(val,elem) {
                console.log(elem.id);
                    var files    =   $('#'+elem.id)[0].files;
                console.log(files);
                for(var i=0;i<files.length;i++){
                    var fname = files[i].name.toLowerCase();
                    var re = /(\.pdf|\.docx|\.doc)$/i;
                    if(!re.exec(fname))
                    {
                        console.log("File extension not supported!");
                        return false;
                    }
                }
                return true;
            },
            "Please upload pdf or doc or docx files"
    );
    // Initialize form validation on the registration form.
    // It has the name attribute "registration"
    $("form[name='formname']").validate({
        // Specify validation rules
        rules: {
            'uploaded_files[]':{
                required: true,
                validate_file_type : true
            }
        },
        // Specify validation error messages
        messages: {

            'uploaded_files[]':{
                required : "Please upload atleast 1 document",
                /*accept:"Please upload .docx or .pdf files"*/
            }
        },
        // Make sure the form is submitted to the destination defined
        // in the "action" attribute of the form when valid
        submitHandler: function(form) {
            form.submit();
        }
    });

});    

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.