Kevin Brown
Kevin Brown

Reputation: 12650

jQuery validation: .each with form

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...

Upvotes: 0

Views: 2481

Answers (2)

Kevin Brown
Kevin Brown

Reputation: 12650

This solves my problem:

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

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134177

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!"
          }
      } 
  }
});

Upvotes: 1

Related Questions