jQuery Validation Plugin - adding rules that apply to multiple fields
Solution 1:
For the purposes of my example, this is the base starting code:
HTML:
<input type="text" name="field_1" />
<input type="text" name="field_2" />
<input type="text" name="field_3" />
jQuery:
$('#myForm').validate({
rules: {
field_1: {
required: true,
number: true
},
field_2: {
required: true,
number: true
},
field_3: {
required: true,
number: true
}
}
});
http://jsfiddle.net/9W3F7
Option 1a) You can pull out the groups of rules and combine them into common variables.
var ruleSet1 = {
required: true,
number: true
};
$('#myForm').validate({
rules: {
field_1: ruleSet1,
field_2: ruleSet1,
field_3: ruleSet1
}
});
http://jsfiddle.net/9W3F7/1
Option 1b) Related to 1a above but depending on your level of complexity, can separate out the rules that are common to certain groups and use .extend()
to recombine them in an infinite numbers of ways.
var ruleSet_default = {
required: true,
number: true
};
var ruleSet1 = {
max: 99
};
$.extend(ruleSet1, ruleSet_default); // combines defaults into set 1
var ruleSet2 = {
min: 3
};
$.extend(ruleSet2, ruleSet_default); // combines defaults into set 2
$('#myForm').validate({
rules: {
field_1: ruleSet2,
field_2: ruleSet_default,
field_3: ruleSet1
}
});
End Result:
field_1
will be a required number no less than 3.field_2
will just be a required number.field_3
will be a required number no greater than 99.
http://jsfiddle.net/9W3F7/2
Option 2a) You can assign classes to your fields based on desired common rules and then assign those rules to the classes. Using the addClassRules
method we're taking compound rules and turning them into a class name.
HTML:
<input type="text" name="field_1" class="num" />
<input type="text" name="field_2" class="num" />
<input type="text" name="field_3" class="num" />
jQuery:
$('#myform').validate({ // initialize the plugin
// other options
});
$.validator.addClassRules({
num: {
required: true,
number: true
}
});
http://jsfiddle.net/9W3F7/4/
Option 2b) The main difference from option 2a is that you can use this to assign rules to dynamically created input elements by calling rules('add')
method immediately after you create them. You could use class
as the selector, but it's not required. As you can see below, we've used a wildcard selector instead of class
.
The .rules()
method must be called any time after invoking .validate()
.
jQuery:
$('#myForm').validate({
// your other plugin options
});
$('[name*="field"]').each(function() {
$(this).rules('add', {
required: true,
number: true
});
});
http://jsfiddle.net/9W3F7/5/
Documentation:
rules('add')
methodaddClassRules
method