views:

292

answers:

2

Hi have two forms with the exact same validation rules, but different ids that I'd like to combine into just one function. How can I do that?

var validator = $("#ValidateForm1").validate({
errorPlacement: function(error, element) {
    if ( element.is(":radio") )
        error.appendTo( element.parent().next().next() );
    else if ( element.is(":checkbox") )
        error.appendTo ( element.next() );
    else
        error.appendTo( element.parent().next() );
}       
});

var validator = $("#validateForm2").validate({
errorPlacement: function(error, element) {
    if ( element.is(":radio") )
        error.appendTo( element.parent().next().next() );
    else if ( element.is(":checkbox") )
        error.appendTo ( element.next() );
    else
        error.appendTo( element.parent().next() );
}       
}); 
A: 

Make the formId as a variable

var myFormId = "ValidateForm1"; // e.g. get the form id by using javascript

....

var validator = $("#"+ myFormId).validate({
errorPlacement: function(error, element) {
    if ( element.is(":radio") )
        error.appendTo( element.parent().next().next() );
    else if ( element.is(":checkbox") )
        error.appendTo ( element.next() );
    else
        error.appendTo( element.parent().next() );
}       
}); 
codemeit
+1  A: 

If you don't need the validator variable (which you're re-defining, so it appears you don't), just use a multiple selector:

$("#validateForm1, #validateForm2").validate({
  errorPlacement: function(error, element) {
    if ( element.is(":radio") )
        error.appendTo( element.parent().next().next() );
    else if ( element.is(":checkbox") )
        error.appendTo ( element.next() );
    else
        error.appendTo( element.parent().next() );
  }       
});

Or, if you have a lot of forms like this, just give them a class and like this:

<form id="validateForm1" class="myFormClass"></form>
<form id="validateForm2" class="myFormClass"></form>
....
<form id="validateFormX" class="myFormClass"></form>

And a selector like this:

$(".myFormClass").validate({
Nick Craver