如何在字段模糊上验证整个表单而不仅仅是模糊字段

How to validate the entire form on field blur instead of just the blurred field

我有一个使用 jQuery 验证的表单,使用不显眼的验证来声明规则。目前我使用的是默认提交行为,在提交表单之前不对模糊进行验证(验证表单中的每个字段),之后后续模糊仅验证模糊字段。

我想更改此行为,以便在提交后模糊单个字段来重新验证整个表单,以便错误摘要保留在屏幕上,直到每个问题都得到解决。提交前的行为应该保持不变。

我已经根据其他 SO 答案尝试了以下 onfocusout 方法,但没有成功:

onfocusout: function(element, event) {
    $(element).valid();
}

onfocusout: function(element, event) {
    this.element(element);
}

this.element(element)$(element).valid()都是针对单个元素触发验证。在你的情况下,由于你试图在 .validate().setDefaults() 方法的选项中应用它,你不能使用 .valid() 因为它可能会触发无限递归。

剩下 .element()。但是,as per the docs,您只能在单个字段上使用它,而不是整个表单。

How to validate the entire form on field blur instead of just the blurred field
I'd like to change this behaviour ... blurring a single field revalidates the entire form

解决方案是编写附加到所有相关输入元素的外部 blur 事件处理程序,并触发附加到表单的 .valid() 方法。编辑此通用示例中适用于您的特定表单的选择器。

$('#myform input[type="text"]').on('blur', function() {
    $('#myform').valid();  // <- trigger validation on entire form
});
  • $('#myform input[type="text"]') 选择 #myform

  • 内的所有文本输入
  • $('#myform') selects theformbased onid="myform"`