jQuery验证AJAX调用后如何手动使字段无效 [英] How to manually invalidate fields after AJAX call with jQuery validate

查看:104
本文介绍了jQuery验证AJAX调用后如何手动使字段无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:以下代码仅用于演示,我正在使用jQuery和jQuery validate插件.

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

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

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>

将插件绑定到表单:

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

推荐答案

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

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

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

其中firstname是您的字段的名称属性;即name="firstname".

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

这篇关于jQuery验证AJAX调用后如何手动使字段无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆