The jQuery validation plugin (jquery.validate.js) supports the method addClassRules(). This allows me to do something like this:
$.validator.addClassRules({
birthdate: {
date: true,
notFuture: true,
notBefore1900: true
}
});
where the notFuture and notBefore1900 are methods I've previously specified with calls to .addMethod().
This allows me to use that by specifying the class: <input class="birthdate" name="foo" />
and it validates just fine, displaying the appropriate validation error message based on the specific method that triggered the invalid state.
My question is how do I do such compound rules and specify them as part of the rules arguments to the validate() method? I want to be able to do this:
$('#myForm').validate({
rules: {
foo: 'birthdate'
}
});
Sadly while validation methods themselves can be represented either as class names or as explicit rules in the arguments like
rules: {
foo: 'date'
}
one cannot do the same with class rules; it expects the rules arguments to validate() to be a method and not a class rule.
I could do something like:
var reusableRule = {
date: true,
notFuture: true,
notBefore1900: true
};
...
$('#myForm').validate({
rules: {
foo: reusableRule
}
});
but I'd prefer to keep things contained within the plugin itself rather than invading the global scope. I could do something like this
$.validator.customRules = {
birthdate: {
date: true,
...
}
}
but then it looks ugly (or at least inconsistent with the syntax of the other rules items):
$('#myForm').validate({
rules: {
foo: $.validator.customRules.birthdate
}
});
Also, I run the risk of a later version of the plugin specifying something like customRules
which would cause a collision.
For now I think I'll keep them in the global scope, but if anyone has a cleaner way (or if there's a 'right way' that I missed when parsing the documentation) please share. Thanks :)