I’ve got multiple forms, all of them share common fields (for example email), and each one has unique fields (for example, uniqueFieldA on Form A, and uniqueFieldB on Form B ).
What I want to do: Write a set of validation rules (using the jQuery Validation Plugin) for the common fields once, and “include” those rules in multiple places (each form), then add in the rules unique to that particular form.
Something like this:
Simplified HTML:
<form id="formA">
<input name="email" />
<input name="uniqueFieldA" />
</form>
<form id="formB">
<input name="email" />
<input name="uniqueFieldB" />
</form>
JS:
// Define rules common to all forms
var commonRules = {
email: {
required: true,
email: true
},
}
// Define rules for form A
$("#formA").validate({
rules: {
commonRules, //"include" common rules
uniqueFieldA: "required" //rule unique to this form
}
})
// Define rules for form B
$("#formB").validate({
rules: {
commonRules, //"include" common rules
uniqueFieldB: "required" //rule unique to this form
}
})
What will achieve this (assuming the full, correct HTML was used)?
Since that’s not syntactically valid JavaScript (JSLint could have told you that), no, it will not work.
$.extendis your friend here. Try this (not tested):You may need to perform a recursive merge (a “deep extend”) if there is any overlap between the common rules and the form-specific ones.