tags:

views:

43

answers:

2

If I have a form of about 40 questions, how do I apply the same rules to questions 1-20, and 21-40?

For example:

$("#form_survey").validate({
    rules: {
        a_ +i: {max:12, maxlength:2},
    },
    messages: {
        a_ +i:{
            max: "That's too much!"
        }

    }   

Where the "+i" is the ideal increment of +1...

Should be easy, I'm just stuck on syntax...

+1  A: 

You could have them all use the same class: class="question". Then, use the class to create the validation:


$(".question").each(function (i) {
  this.validate({
      rules: {
          a_ +i: {max:12, maxlength:2},
      },
      messages: {
          a_ +i:{
              max: "That's too much!"
          }
      } 
  }
});
Justin Ethier
I have to pass rules to the field, right? It doesn't automatically apply validation rules to these classes...Maybe you could explain a bit more?
Kevin Brown
Hmm... I was hoping that this would apply them to all of the fields using the target class. But if that is not the case then another method would be required. Maybe you could still use the class to iterate over the fields with `each`, and then call into your code for each object?
Justin Ethier
That's what I'm going for, I think. If you could help with the code, I'd be thrilled!
Kevin Brown
I edited the code above - does that help?
Justin Ethier
This looks closer, but this throws an error: "Missing : after property id"
Kevin Brown
A: 

This solves my problem:

$('.text-input').addClass('hours');
jQuery.validator.addClassRules("hours", {
  required: true,
  minlength: 2
});
Kevin Brown