views:

106

answers:

4

I have about 40 questions in a survey that need to be validated all the same way. What's the easiest way to do this without writing every validation down?

For example: Every question must be a natural number, maxlength of 2, and value less than 12.

Using jQuery validation

A: 

Without any code it is hard to help. Most likely a for loop will do or jQuery's each method.

Or maybe the jQuery Validation PLugin.

Felix Kling
A: 

without any details on your code - something like this could be a starting point:

$('.class-of-your-validation-elements').each(function() { your_validation_code($(this)); }
roman
A: 

Add a class to all the validators, then in your loading function, attach the validation function, e.g.

function validationFunction(e)
{
    $(this).val() > 5;
}

$(function() {
    $('.validators').bind('blur', validationFunction);
}
Khanzor
A: 

you can easily ad an onsubmit method to your form, like this:

$().ready(function() {
    $('form').submit(function() {//adds a javascript check to the form's submit
         $('form input').each(function() {//this loops through each input in the form
              var inputValue = parseInt($(this).val(), 10);
              if (inputValue < 12) { hideErrors();}
              else { displayErrors(); return false;}
         });
    });

});

Hope this helps.

the validation plugin mainly works when you add classes to existing inputs, my above method will loop through any inputs in the form without a need to add classes to all of the inputs

Jimmy