2011-12-05 177 views
2

我正在使用下面的代碼來驗證我的表單。驗證過程很順利,但在提交表單時遇到問題。問題是:無論表單是否經過驗證,每次單擊「發送表單」按鈕時都會將表單提交給php文件。jQuery驗證:僅在字段驗證時提交表單

我該如何解決這個問題?

我一直在研究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

您需要將您的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.

+0

是的!太感謝了!! – user523129

+0

沒問題,很高興幫助:) –