This regarding the JQuery validation plugin. I have a custom method like this.
$.validator.addMethod("USphoneCheck", function(value, element) {
var phoneNumberPattern = /^\(?(\d{3})\)?[-]?(\d{3})[-]?(\d{4})$/;
return phoneNumberPattern.test(value);
}, "Please enter a valid US phone number.");
This is my function call
cus_phone: {
required: false,
minlength: 12,
USphoneCheck: true
},
When I run the code without any value I get "Please enter a valid US phone number" message.
This is not required field, But I want to validate when someone entered a value. Am I doing something wrong? Appreciate your help.
Thanks
if (value !== '') { //do the validation }this.optional(element)within yourreturnstatement.return this.optional(element) || phoneNumberPattern.test(value)This simply makes it "optional". In other words, if you later wanted the field to be required, simply addrequired: trueto the rule declaration without touching this custom method. See the answer within the duplicate.