Title: ... custom logical operators (=> rule1 OR rule2 OR rule3…)
When you declare rules for this plugin, it will apply ALL rules that are declared using a logical AND.
rules: {
myField: {
digits: true,
//required: false, // <- 'false' is superfluous/default
maxlength: 9999,
myCustomRule: true
}
}
The above states that this field must satisfy digits
AND maxlength
AND myCustomRule
; AND it will not be required
if myCustomRule
is properly written.
There is no option within this plugin to change "AND" into "OR" when evaluating the list of declared rules.
The only way you can evaluate the rules using an OR operator is by creating a single custom rule that encompasses all of your validation logic into one function.
rules: {
myField: {
myCustomRule: true
}
}
Where myCustomRule
contains your own function with all rule logic separated by OR operators. See below for the solution to your exact example.
... how can I define a field that can be blank OR digits OR "foo" ?
You must create a custom rule that does all three within one function.
blank: This is considered "optional" and when you create your own custom rule, it will not allow the field to remain blank unless you compare the result to this.optional(element)
using an OR operator.
"foo": Use value === "foo"
digits: Just use the code for the existing digits
rule, /^\d+$/.test(value)
Then string it all together using OR operators...
$.validator.addMethod("myCustomRule", function(value, element) {
return this.optional(element) || value === "foo" || /^\d+$/.test(value);
}, "myMessage");
Everything is contained within this new custom rule, so you must not declare any other rules...
var myValidator = $("#myFormId").validate({
rules: {
myField: {
myCustomRule: true
}
}
});
The result is an "optional" field that will also validate for digits or the string "foo".
DEMO: jsfiddle.net/tLoef0ov/