Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validation-plugin: validating multiple input files

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);
        }           
    });
}
like image 228
user4815740 Avatar asked May 07 '15 07:05

user4815740


2 Answers

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.

like image 72
Ashot Khanamiryan Avatar answered Oct 04 '22 22:10

Ashot Khanamiryan


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();
        }
    });

});    
like image 27
Kiran Sadvilkar Avatar answered Oct 04 '22 20:10

Kiran Sadvilkar