简体   繁体   中英

Validate and submit a form containing data and a file using ajax/jquery

I have a form containing data and a file input fields, I want to submit and validate this form using jquery and ajax through one script.

Below is my form:

<form id="datas" method="post" enctype="multipart/form-data">
    <input type="text" name="firstName" value="" />
    <input name="pic" type="file" />
    <button>Submit</button>
</form>

Now I have this code to validate the data

$('#datas').validate({
    rules: {
        firstName:{
            required: true,
            minlength: 2,
            maxlength: 100
        }   

    },
    messages: {
        firstName: {
            required: "Please Enter first name",
            minlength: jQuery.format("Enter at least {0} characters"),
            maxlength: jQuery.format("Enter atmost {0} characters"),
        }
    }
});

Then I have a seperate code that could submit the form

$("#datas").submit(function(){

    var formData = new FormData($(this)[0]);

    $.ajax({
        url: sucess.php,
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });
});

QUESTION:

Please how can I combine these two scripts to validate the file and data fields and also submit to the success page.

You can set required attribute for the file field as well as such:

   rules: {
        ...
        pic:{
            required: true
        },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM