Question

Having two fields in my form, that compare to each other to see if they are valid:

<input type="text" name="StartDate" id="StartDate" value="2"
       data-val="true" data-val-equalto="xx" data-val-equalto-other="EndDate"/>   
<input type="text" name="EndDate" id="EndDate" value="3"
       data-val="true" data-val-equalto="xx" data-val-equalto-other="StartDate"/> 

When I blur on StartDate, EndDate gets validated as well. So jQuery manages to avoid validation loop between one and the other.

Now, I am trying to implement the same mechanism in my custom validation rules. I get the value from the "other" field, and if everything is right, i trigger validation in the "other" as well, but this ends in a validation loop:

$.validator.addMethod("customequal-method", function (val, el, p) {
    var $other = $(el).closest('form').find('input[name=' + p.other + ']'); 
    if($other.val() == val){        
        try{$other.valid();}
        finally{return true;}
    }
    return false;
});

How could I apply the same approach than jQuery? I mean, given these two fields:

<input type="text" name="StartDate2" id="StartDate2" value="2"
       data-val="true" data-val-customequal="xx xxx" data-val-customequal-other="EndDate2"/>   
<input type="text" name="EndDate2" id="EndDate2" value="3"
       data-val="true" data-val-customequal="xx xx" data-val-customequal-other="StartDate2"/> 

I want that when modifying EndDate2, after blur, StartDate2 gets validated as well, and both became valid in the same way than in jQuery.

I have been trying to put together an example in jsFiddle, but I cannot make my custom method work: http://jsfiddle.net/vtortola/vu6tm/ ( if you find the problem I would be very grateful ), I started a separate thread about this at jQuery unobtrusive custom adapter and method in jsFiddle

Cheers.

Was it helpful?

Solution

You need a stack to understand you returned back to a previously validates element. A single value is not enough because eache element may be involved in other rules with other elements. You may define the var that contains the stack in closure (isInStack verifies if the element is in the array):

(function () {
var stack = [];
$.validator.addMethod("customequal-method", function (val, el, p) {
var iAmTheRoot = stack.length == 0;
var $other = $(el).closest('form').find('input[name=' + p.other + ']'); 
if($other.val() == val){        
    try{
      if (!isInStack($other[0]) ) $other.valid();
    }
    finally{
    if (iAmTheRoot) stack = [];
    return true;}
}
return false;
});})();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top