jQuery验证:仅在验证字段时提交表单

时间:2011-12-05 10:09:24

标签: jquery ajax serialization jquery-validate form-submit

我正在使用以下代码验证我的表单。验证很顺利但提交表单时遇到问题。问题是:每次单击“发送表单”按钮时,表单都会提交到php文件,无论表单是否未经过验证。

我该如何解决?

我一直在研究submitHandler,但我不知道如何将它与ajax和序列化一起使用..

非常感谢!

<script>
$(document).ready(function(){
   $("#form").validate({
      rules: {
         name: {
           required: true
         },
         lname: {
           required: true
         }

      },
      messages: {
         name: {
           required: "* required"
         },
         lname: {
           required: "* required"
         }
      }

   }); //end validate

  $('#form').submit(function() {

    theUrl = 'form.php';

     var params = $(this).serialize();
    $.ajax ({
            type: "POST",
            url: theUrl,
            data: params,
            processData:false,
            async:false,
            success: function(result) {

                //if (data != "") alert (data);
            }
    });
    //return false;
  }); //end submit

});    //end document ready 



</script>

1 个答案:

答案 0 :(得分:1)

您需要将AJAX请求代码放在validate插件的submitHandler参数中。目前,AJAX请求正在submit()事件上运行,与任何验证结果并行。试试这个:

$(document).ready(function(){
    $("#form").validate({
        rules: {
            name: { required: true },
            lname: { required: true }
        },
        messages: {
            name: { required: "* required" },
            lname: { required: "* required" }
        },
        submitHandler: function(form) {
            theUrl = 'form.php';
            var params = $(form).serialize();

            $.ajax ({
                type: "POST",
                url: theUrl,
                data: params,
                processData: false,
                async: false,
                success: function(result) {
                    //if (data != "") alert (data);
                }
            });
        }
    }); //end validate
});

More information on the submitHandler parameter.