jdepypere
jdepypere

Reputation: 3553

jQuery Validation plugin rules to specific form

I'm using the jQuery Validation plugin to validate my forms. Now I want to validate each form on my site. This works:

$('form').validate({
    <?php echo $translation["validation_lang"];?>
    errorPlacement: function (error, element) {
        $(element).tooltipster('update', $(error).text());
        $(element).tooltipster('show');
    },
    success: function (label, element) {
        $(element).tooltipster('hide');
    }
});

I'm using Tooltipster to show the errors next to their corresponding field. Again, this works. The PHP-string in there is to optionally load a language pack.

Now I have other forms on my site that require additional rules. For example, the register form should check username availability, check username validity (length, characters, ...), etc.

$('#registerForm').validate({
    rules: {
        username: {
            minlength: 3,
            maxlength: 50
        },
        password1:  {
            minlength: 5
        },
        password2:  {
            minlength: 5,
            equalTo: "#password1"
        },
        email: {
            remote:{
                url: "getContent.php",
                type: "post",
                data: {
                    type: "checkMail"
                }
            }
        },
        username:   {
            remote: {
                url: "getContent.php",
                type: "post",
                data:   {
                    type: "checkUser"
                }
            }
        }
    },
    messages:   {
        email:  {
            remote: "<?php echo $translation["already_registered"][0];?>"
        },
        username:   {
            remote: "<?php echo $translation["already_registered"][1];?>"
        }
    }
});

Having these two snippets of code on the same page does not work. When having the body of the code above (thus the rules and messages) inside the initial $('form').validate({ instead of it's own $('#registerForm').validate({ it does work. I can't seem to find anywhere how to add certain rules to specific form's, whilst maintaining the 'general' rules for all forms.

So in short: How do I add rules/messages/submitHandlers to specific forms with a certain ID, whilst maintaining the general form-rules?

Upvotes: 0

Views: 2004

Answers (1)

Tigran Petrossian
Tigran Petrossian

Reputation: 1168

You can use the setDefaults method to define common validation stuff: http://jqueryvalidation.org/jQuery.validator.setDefaults/

Example:

$.validator.setDefaults({
    errorPlacement: function (error, element) {
    $(element).tooltipster('update', $(error).text());
    $(element).tooltipster('show');
},
    success: function (label, element) {
    $(element).tooltipster('hide');
}
});

jsFiddle - Setting error element to "em" for all forms.

Upvotes: 1

Related Questions