如何处理jQuery验证错误

时间:2015-03-08 04:08:58

标签: jquery jquery-validate

我有一个表单,我正在验证其中的一些必填字段。我正在使用jquery.validate插件来验证表单。以下是片段: JS:

    var validator = $("#accountCreateForm").validate({

    // Specify the validation rules
    rules: {
        firstname: "required",
        lastname: "required",
        email: {
            required: true,
            email: true
        }
    },

    // Specify the validation error messages
    messages: {
        firstname: "Please enter your first name",
        lastname: "Please enter your last name",

        email: "Please enter a valid email address"
    }

});
$('#button').on("click", function(){
  $.wm.net.restRequest('/account/data',{
     //post the required data
  }).fail(function() {
    // do the error handling
  }).done(function() {
    //post data successfully
   });
 });

HTML:

 <form action="" method="post" id="register-form" >

<div class="label">First Name</div><input type="text"  name="firstname" /><br />
<div class="label">Last Name</div><input type="text" id="lastname" name="lastname" /><br />
<div class="label">Email</div><input type="text" id="email" name="email" /><br />
  <div style="margin-left:140px;"><button id="button" type="submit" name="submit" >Submit</button></div>

 </form>

通过上面验证插件的初始化,表单不会验证,主要是因为我没有在错误处理函数中做任何事情。我不知道如何处理错误函数的验证:

}).fail(function() {
    // do the error handling
  });

谢谢!

1 个答案:

答案 0 :(得分:0)

您的表单名称是&#39;注册表单&#39;,但您正在验证&accountCreateForm&#39;。

在这里,我用你的表单尝试了这个,这对我有用:

var validator = $("#register-form").validate({

    // Specify the validation rules
    rules: {
        firstname: "required",
        lastname: "required",
        email: {
           required: true,
           email: true
        }
    },

    // Specify the validation error messages
    messages: {
        firstname: "Please enter your first name",
        lastname: "Please enter your last name",
        email: "Please enter a valid email address"
    }

});

$('#button').on("click", function(){

    if($('#register-form').valid()) 
    {
        /*  Do your saving, etc stuffs here */
        $('#register-form').submit();

    }

});