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_2" />
JS:
$('#myForm').validate({
rules: {
field_1: {
required: true,
number: true
},
field_2: {
required: true,
number: true
},
field_3: {
required: true,
number: true
}
}
});
Option 1) You can assign classes to your fields based on desired common rules and then assign those rules to the classes. You can also assign custom messages.
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" />
The .rules()
method must be called after invoking .validate()
JS:
$('#myForm').validate({
// your other plugin options
});
$('.num').each(function() {
$(this).rules('add', {
required: true,
number: true,
messages: {
required: "your custom message",
number: "your custom message"
}
});
});
Option 2a) 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
}
});
Option 2b) Related to 2a 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
var ruleSet3;
$.extend(ruleSet3, ruleSet_1, ruleSet_2); // combines sets 2 & 1 into set 3. Defaults are included since they were already combined into sets 1 & 2 previously.
$('#myForm').validate({
rules: {
field_1: ruleSet2,
field_2: ruleSet_default,
field_3: ruleSet1,
field_4: ruleSet3
}
});
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.
-
field_4
will be a required number between 3 and 99.