jQuery验证表单错误并将其链接到各自的字段

时间:2012-07-11 19:22:54

标签: jquery jquery-validate

我正在使用jQuery Validate,我将表单拆分为多个部分。提交时它会验证,我将返回包含所有错误的错误框方法。我希望能够将它们指定为链接,因此单击错误会将用户带到该字段。开箱即用?

JS:

$('#form').validate({
    rules: {
        firstname:   {required: true},
        lastname:    {required: true},
        email:       {required: true},
    },
    messages: {
        firstname:   {required: "Step 2: Your first name is required."},
        lastname:    {required: "Step 2: Your last name is required."},
        email:       {required: "Step 2: Your email is required."},
    },
    errorContainer: "#error_container",
    errorLabelContainer: "#error_container ul",
    wrapper: "li",
    submitHandler: function() {
            ajax('{{=URL('new_post')}}',
    }
});

它生成的HTML看起来像:

<div id="error_container">
    <ul><li><label for="firstname" generated="true" class="error_two" style="display: inline;">Step 2: Your first name is required.</label></li></ul></div>

如果可能的话,我希望将其链接回firstname字段。感谢。

编辑:我看到我没有很好地解释自己。我希望生成的HTML将是:

<div id=error_container">
    <ul>
        <li>
            <a href="link_to_field">Your first name is required.</a>
        </li>
    </ul>
</div>

它创建可点击的锚点返回相应的字段。有什么办法吗?我已经看到下面列出的“关注错误”方法,这当然是一个很好的方法,但我希望能够让用户点击任何错误并按任意顺序转到这些字段选择。它以多步格式工作,这就是我想要的原因,否则,它就会在那里,他们可以正常点击每个字段。

1 个答案:

答案 0 :(得分:1)

  • 快速方法是使用validate选项focusInvalid,它会将最后一个活动元素或第一个无效元素集中在提交

    $('#form').validate({
       .
       focusInvalid: true,
       .
    });
    
  • 漫长的道路,应该实现你想要做的,就是在验证选项中使用showError回调

    $('#form').validate({
       .
       showErrors: function(errorMap, errorList) {
           // errorMap - the map of errors
           // errorList - array of errors
           // construct the list of error items with links that focus on the invalid elements
    
           // default behavior
           this.defaultShowErrors();
       },
       .
    }