Question

Users are allowed to add as many inputs as they want, where the input fields look like this:

<input id="minAge[0]"...
<input id="maxAge[0]"...

<input id="minAge[1]"...
<input id="maxAge[1]"...

<input id="minAge[2]"...
<input id="maxAge[2]"... etc

Problem

I want to validate for each pair of inputs (minAge[i],maxAge[i]) that the maxAge is greater than minAge.

Specific solution

$.validator.addMethod('lessThan', function(value, element, param) {
    if (this.optional(element)) return true;
    var i = parseInt(value);
    var j = parseInt($(param).val());
    return i < j;
}, "MinAge must be less than MaxAge");


$('#form').validate({
    rules: {
        minAge: {
            lessThan: '#maxAge'
        }
 });

How can I make this solution generic?

Was it helpful?

Solution 2

A small fix to the solution above:

For the jquery validation will fail. try to use the name xxx[i] and id xxx_i, and in the rules it deals with id so change the code to:

var min = '#minAge_' + i,
    max = '#maxAge_' + i;

$(min).rules('add', {
    required: true,
    lessThan: max,
    // another rule, etc.
});

OTHER TIPS

First of all, for this plugin, you must have name attributes. The jQuery Validation plugin requires unique name attributes to keep track of all inputs.

<input id="minAge[0]" name="minAge[0]"...
<input id="maxAge[0]" name="maxAge[0]"...

<input id="minAge[1]" name="minAge[1]"...
<input id="maxAge[1]" name="maxAge[1]"...

<input id="minAge[2]" name="minAge[2]"...
<input id="maxAge[2]" name="maxAge[2]"... etc

Then within whatever function you use to dynamically add fields, you would use the .rules('add') method.

$('#minAge[1]').rules('add', {
    required: true,
    lessThan: '#maxAge[1]',
    // another rule, etc.
});

Since I cannot see the function that creates your new element, I can only assume you have some kind of index variable.

var min = '#minAge[' + i + ']',
    max = '#maxAge[' + i + ']';

$(min).rules('add', {
    required: true,
    lessThan: max,
    // another rule, etc.
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top