【问题标题】:How to manually invalidate fields after AJAX call with jQuery validate如何在使用 jQuery 验证的 AJAX 调用后手动使字段无效
【发布时间】:2011-10-09 03:19:51
【问题描述】:

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

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

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

【问题讨论】:

  • 您找到解决方案了吗?这正是我目前正在尝试做的事情。
  • 我找到了解决方案,请给我一些时间,我会告诉你

标签: jquery jquery-validate


【解决方案1】:

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

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

firstname 是字段的名称属性;即name="firstname"

【讨论】:

  • 这会显示错误但表单仍会提交
  • 从提交函数返回 false $('#sample-form').submit(function(){ return false;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多