jQuery validation plugin addMethod firing incorrectly
- by LoganEtherton
I must be missing something obvious, but everything that I've tried for this is leaving me empty handed, so I'm a bit puzzled.
I'm attempting to use the jQuery validation plugin with custom validation methods, but it seems to be hit or miss. It seems that I am able to successfully add rules to a certain extent, but some of the methods are not applied. Or the specified method is not applied, and the incorrect method is instead applied.
So, for example, this works without a hitch:
$.validator.addMethod("emailValidation",
function(value, element) {
return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/.test(value);
},
"Please enter a valid email address."
);
$.validator.addMethod("password",
function(value, element) {
return /[^\s]{6,25}/.test(value);
},
"Please enter a password between 6 and 25 characters long."
);
...
$(function(){
$("#registrationForm").validate({
rules: {
email: {
required: true,
emailValidation: true
},
password: {
required: true,
password: true
},
}
});
});
Both the password validation and email validation work.
But then I add, in the same exact manner, a validation test for names. So, right below where the password method ends, I add:
$.validator.addMethod("name",
function(value, element) {
return /[^\s]{6,25}/.test(value);
},
"Please enter a valid name."
);
Which turns the validate call into:
$(function(){
$("#registrationForm").validate({
rules: {
email: {
required: true,
emailValidation: true
},
password: {
required: true,
password: true
},
studentFirstName: {
name: true
}
}
});
});
And suddenly, everything is only validating for names. Both the email and password fields now validate using the name method, as does the name field.
This is confusing! I've added console.log calls to all methods, and indeed, it's not that one is being called after the other - the only one being called is name.
I've checked and double checked that the element selection is good. I've checked that everything is groovy with the methods themselves. Any ideas?