Validate other field without causing infinite loop

2019-07-20 04:56发布

问题:

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?

回答1:

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.



回答2:

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.