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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6758036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:21:08  来源:igfitidea点击:

How to manually invalidate fields after AJAX call with jQuery validate

jqueryjquery-validate

提问by Praveen Prasad

Note: the below code is just for demonstration and I am using jQuery and jQuery validate plugin.

注意:以下代码仅用于演示,我使用的是 jQuery 和 jQuery 验证插件。

Suppose I have a form with two fields (email and inventory number):

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

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

Binding plugin to form:

将插件绑定到表单:

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
                */
            }
        });
    }
});

回答by iboware

If you know which field is invalid, you can use this function. http://docs.jquery.com/Plugins/Validation/Validator/showErrors

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

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

Where firstnameis the name property of your field; ie name="firstname".

firstname您的字段的名称属性在哪里;即name="firstname"