In a registration form middleName field is optional. When the users enters his/her middleName, then it should validate that field.
I have used the following code to achieve the above scenario, but it is not working.
$("#middleName").rules("add", {checkName: true, required: false, messages: {checkName: "Please enter a valid middle name"} });
jQuery.validator.addMethod("checkName",
function(value, element) {
var regExp = new RegExp(/^[a-zA-Z0-9\s|\,|\.|\-|\']+$/);
return regExp.test(value);
},
"Please enter a valid name."
);
Can anyone suggest me to achieve the above scenario.
In your custom methods you need to add the optional clause, like this:
You can see examples like this in the validation library’s additional methods file as a reference, basically this just adds a sanity/”am I even required?” check to the result.