Developer // jQuery Validate: Custom Validator for correct Email format

When using jQuery validate on a form it was picked up that the email field was not checking the length of each section, just the format ‘e.g. a@b.c’.

After googling it was suggested that a custom validator was the best solution to this issue.

//custom validator method to apply regex to email field validation
jQuery.validator.addMethod("emailCustom", function (value, element, params) {
var re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@((
[[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
return re.test(value);
}, "Please enter a valid email address.");

Adding the above validator to my script file and then referencing it from the rules for the email field (below), fixed the problem

rules:{
'first_name': "required",
'last_name': "required",
'company_name': "required",
'email': {
required: true,
emailCustom: true
}......

Leave a comment