使用jQuery验证AJAX调用后如何手动使字段无效

Pra*_*sad 17 jquery jquery-validate

注意:下面的代码仅用于演示,我使用的是jQuery和jQuery validate插件.

假设我有一个包含两个字段的表单(电子邮件和库存号):

<form action="/something" method="post" id="demoForm">
     Inventory No: <input type="text" class="required" name="inventory_no" />
     Email: <input type="text" class="required" name="email" />
     <input type='submit' value='submit' />
</form>
Run Code Online (Sandbox Code Playgroud)

绑定插件形成:

jQuery(function(){
    jQuery('#demoForm').validate();
});

//handle user submit

jQuery('#demoForm').bind('submit', function (e) {
    e.preventDefault();

    if (jQuery(e.target).valid()) {
        //form is valid submit request thru ajax

        jQuery.ajax({
            /*more options here*/

            success: function (data) {

                /*
                 Server process request and finds that, email is already in use
                 and inventory number is invalid
                 so it sends data in some format may pe JSon
                 with field names and message indicating errors
                 eg: Email:"Already in use"
                 InventoryNo: "Invalid Inventory No",
                 Now can i invalidate these two fields on form mannualy
                 and display the message received from server for each field
                */
            }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

ibo*_*are 36

如果您知道哪个字段无效,则可以使用此功能. http://docs.jquery.com/Plugins/Validation/Validator/showErrors

var validator = $( "#myshowErrors" ).validate();
validator.showErrors({
  "firstname": "I know that your firstname is Pete, Pete!"
});
Run Code Online (Sandbox Code Playgroud)

firstname你所在领域的名称属性在哪里; 即name="firstname".

  • 这将显示错误,但表单仍将提交 (21认同)