0

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?

1
  • Also show the function that dynamically creates the new elements. Commented Apr 3, 2014 at 18:11

2 Answers 2

2

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.
});
Sign up to request clarification or add additional context in comments.

1 Comment

this almost works, i can see that the input elements are generated, but when i run the rules('add') I get uncaught exception: Uncaught TypeError: Cannot read property 'form' of undefined. According to the documentation of rules: "Requires that the parent form is validated, that is, $( “form” ).validate() is called first." All the inputs generated (only these) are included in <form> element. What could be there problem?
1

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

1 Comment

This is no different than my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.