使用jquery.validate执行验证

时间:2011-12-01 23:55:12

标签: jquery validation 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 个答案:

答案 0 :(得分:1)

您可以在验证码上致电form(),请参阅http://docs.jquery.com/Plugins/Validation/Validator/form

因此,您需要更新代码以存储验证器,同样,您应该使用jquery事件连接来捕获按钮上的单击:

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