验证其他字段而不会导致无限循环 [英] Validate other field without causing infinite loop

查看:133
本文介绍了验证其他字段而不会导致无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一种情况下,我正在创建一个不打扰的验证器,该验证器仅在验证字段不为空时才必须验证是否需要另一个字段(反之亦然).问题是,在某些极端情况下,其他字段不会重新验证,我想强迫它重新验证自身而不会引起无限循环.

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.

我的验证方法如下:

$.validator.addMethod("jqiprequired", function (value, element, params) {
    if (!this.optional(element) || (this.optional(params) && this.optional(element))) {
        return true;
    }

    return false;
});

params是我的另一个字段(都是文本框).如果两个都为空,则通过;如果两个都具有值,则通过.仅当只有一个值时,它才会失败.

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

我尝试这样做:

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.

如何在不调用原始字段的情况下使另一个字段进行验证?

推荐答案

与其在每个字段中添加属性,不如在要添加此验证方法的脚本中添加变量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:

var jqip_calledFromOtherValidator = false;
if (jqip_validating) {
    jqip_validating = false;
    jqip_calledFromOtherValidator = true;
}
if (!this.optional(element) || (this.optional(params) && this.optional(element))) {
    if (!jqip_validating && !jqip_calledFromOtherValidator) {
        jqip_validating = true;
        $('form').validate().element(params);
    }
    return true;
}

要调用另一个验证器,必须满足两个条件,并且只有在第一个验证器调用第二个验证器时才能满足.

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.

这篇关于验证其他字段而不会导致无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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