2011-12-01 68 views
1

我在學習/理解jquery.validate的客戶端驗證。目前,我這裏列出的規定爲基本形式:用jquery.validate執行驗證

<form id="myform"> 
    <input id="firstNameTextBox" type="text" /> 
    <input id="lastNameTextBox" type="text" /> 
    <input type="button" value="Test" onclick="return testButtonClick();" /> 
</form> 

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#addPersonForm").validate({ 
      rules: { 
       firstNameTextBox: "required", 
       lastNameTextBox: "required" 
      }, 
      messages: { 
       firstNameTextBox: "Please enter the first name.", 
       lastNameTextBox: "Please enter the last name." 
      } 
     }); 
    }); 

    function testButtonClick() { 
     string errorMessage = validateFormAndGetMessage(); 
     alert(errorMessage); 
     return false; 
    } 
</script> 

當有人點擊「測試」按鈕,我想確定形式是有效的。如果它無效,我想顯示與違規規則相關的消息。我該怎麼做呢?

回答

1

您可以在驗證調用form(),看到http://docs.jquery.com/Plugins/Validation/Validator/form

所以,你需要更新你的代碼來存儲驗證,同時,你應該使用jQuery的事件wireup捕捉按鈕上點擊:

<form id="myform"> 
    <input id="firstNameTextBox" type="text" /> 
    <input id="lastNameTextBox" type="text" /> 
    <input type="button" value="Test" id="testbutton" /> 
</form> 

<script type="text/javascript"> 
$(document).ready(function() { 
    validator = $("#addPersonForm").validate({ 
     rules: { 
      firstNameTextBox: "required", 
      lastNameTextBox: "required" 
     }, 
     messages: { 
      firstNameTextBox: "Please enter the first name.", 
      lastNameTextBox: "Please enter the last name." 
     } 
    }); 

    $('#testbutton').click(function(event) { 
     event.preventDefault(); 
     validator.form(); //This will show the validation messages on the form  
    }); 
}); 
</script>