简体   繁体   English

使用ajax / jquery验证并提交包含数据和文件的表单

[英]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. 我有一个包含数据和文件输入字段的表单,我想通过一个脚本使用jquery和ajax提交并验证此表单。

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
        },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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