Extending PeterTheNiceGuy's answer a bit:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
This would allow you to pass a regex object to the rule.
$("Textbox").rules("add", { regex: /^[a-zA-Z'.\s]{1,40}$/ });
Resetting the lastIndex
property is necessary when the g
-flag is set on the RegExp
object. Otherwise it would start validating from the position of the last match with that regex, even if the subject string is different.
Some other ideas I had was be to enable you use arrays of regex's, and another rule for the negation of regex's:
$("password").rules("add", {
regex: [
/^[a-zA-Z'.\s]{8,40}$/,
/^.*[a-z].*$/,
/^.*[A-Z].*$/,
/^.*[0-9].*$/
],
'!regex': /penis|password|123/
});
But implementing those would maybe be too much.