views:

16

answers:

1

I'm using the jQuery validate plugin to validate a form with a lot of fields:

<td><input name="first_name0"></td>
<td><input name="last_name0"></td>
<td><input name="age0"></td>
<td><input name="first_name1"></td>
<td><input name="last_name1"></td>
<td><input name="age1"></td>
<td><input name="first_name2"></td>
<td><input name="last_name2"></td>
<td><input name="age2"></td>
...
<td><input name="first_name200"></td>
<td><input name="last_name200"></td>
<td><input name="age200"></td>

What's the best way to add validation rules to all of the identical fields? Currently I'm adding rules like this, however it's very slow after 100 rows.

$("input[name*=age]").each(function(i) {
    $(this).rules("add", {
        digits: true
    });
});

$("input[name*=first_name], input[name*=last_name]").each(function(i) {
    $(this).rules("add", {
        digits: true
    });
});
+2  A: 

There's no need to loop, it'll operate on a Query set, like this:

$("input").filter("[name*=age], [name*=first_name], [name*=last_name]")
          .rules("add", {
             digits: true
          });

Giving them a class would be a bit more maintainable, for example:

<td><input name="first_name0" class="digits"></td>
<td><input name="last_name0" class="digits"></td>
<td><input name="age0" class="digits"></td>

Then you could do this:

$("input.digits").rules("add", {
  digits: true
});
Nick Craver
Most of the Validate methods can just be referenced as Nich as done above. I found that the equalTo needed to be added as a rule within a script block.
SidC