验证其他字段而不导致无限循环
我遇到的情况是,我正在创建一个不显眼的验证器,它必须验证仅当已验证字段不为空时才需要另一个字段(反之亦然)。问题是,在某些边缘情况下,其他字段不会重新验证,我想强制它重新验证自身,而不会导致无限循环。
我的验证方法如下所示:
$.validator.addMethod("jqiprequired", function (value, element, params) {
if (!this.optional(element) || (this.optional(params) && this.optional(element))) {
return true;
}
return false;
});
params 是我的另一个字段(都是文本框)。如果两者都为空,则通过;如果两者都有值,则通过。仅当只有一个具有值时才会失败。
这工作正常,但如果一个字段为空,而另一个字段有值,那么您从有值的字段中删除该值,空字段不会重新验证(因为它的值没有更改)。
我尝试这样做:
if (!this.optional(element) || (this.optional(params) && this.optional(element))) {
$('form').validate().element(params);
return true;
}
但这会导致无限循环,因为每次通过时,它都会调用另一个。
如何在不调用原始字段的情况下使其他字段进行验证?
I have a situation where I am creating an unobtrusive validator that must validate that another field is required only if the validated field is not empty (and vice versa). The problem is that there are some edge cases where the other field does not re-validate, and I would like to force it to revalidate itself without causing an infinite loop.
My validation method looks like this:
$.validator.addMethod("jqiprequired", function (value, element, params) {
if (!this.optional(element) || (this.optional(params) && this.optional(element))) {
return true;
}
return false;
});
params is my other field (both are textboxes). If both are empty, it passes, if both have values, it passes. It only fails if only one has a value.
This works fine, except that if one field is empty, and another has a value, then you delete the value from the field with a value, the empty field is not revalidated (because it's value has not changed).
I tried doing this:
if (!this.optional(element) || (this.optional(params) && this.optional(element))) {
$('form').validate().element(params);
return true;
}
But this causes an infinite loop because each time it passes, it calls the other.
How can I cause the other field to validate, without itself calling the original field?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要向每个字段添加属性,而是尝试在要添加此验证方法的脚本中添加变量
jqip_validating
。然后,按如下方式更改您的验证:为了调用另一个验证器,必须满足这两个条件,并且只有当第一个验证器调用第二个验证器时才能满足它们。
Instead of adding an attribute to each field, try adding a variable
jqip_validating
in the script where you are adding this validation method. Then, change your validation as follows:In order for the other validator to be called, both conditions must be satisfied, and they can only be satisfied when the first validator invokes the second validator.
您可以向每个字段添加一个
is_validating
属性,这样,如果该属性打开,则跳过验证,如果没有,则将其设置为 true,进行验证,然后清除它。You can add a
is_validating
attribute to each fields so that, if it's on you skip the validation and if not, you set it to true, do your validation and then clear it.