Gerard Donnelly

A cleaner way to write this email validation code?

Discussion created by Gerard Donnelly on Nov 14, 2019
Latest reply on Nov 15, 2019 by Tony Mayse

Hi Guys, 

Can anyone help me slim down this code I came across? 

 

It checks for both business emails ( I know its not all free emails, just the usual ones its checking) and a valid email address. 

The issue I see is that you need to insert all the email possibilities i.e. "yahoo.com",  "yahoo.co.uk". I think it would be better to make the validation check for contains "yahoo". 

Love to know your thoughts or advice?

 

<script>

MktoForms2.whenReady(function(form) {
form.onValidate(function(builtInValid) {
if (!builtInValid) return;
form.submittable(true);

var vals = form.vals();
var invalidDomains = ["gmail.com", "gmail.co.uk",
"gmail.om", "yahoo.co", "yahoo.com", "yahoo.co.uk",
"hotmail.cm", "hotmail.co", "hotmail.com", "hotmail.co.uk",
"outlook.cm", "outlook.co", "outlook.com", "outlook.co.uk",
"aol.cm", "aol.co", "aol.om", "aol.com", "live.com", "live.co"
],

emailExtendedValidationError =
'Please enter a Business email address.',

emailExtendedValidationError1 =
'Email seems to be incorrect.',

emailField = 'Email',
emailFieldSelector = '#' + emailField;
var invalidDomainRE = new RegExp('@(' + invalidDomains.join(
'|') + ')$', 'i');
if (invalidDomainRE.test(form.vals()[emailField])) {
form.showErrorMessage(emailExtendedValidationError,
form.getFormElem().find(emailFieldSelector)
);
form.submittable(false);
}

var emailRegExp =
/^[^\s@]+@([^\s@.,]+\.)+[^\s@.,]{2,}$/;

var validEmail = emailRegExp.test(vals.Email);
if (!validEmail) {
form.showErrorMessage(emailExtendedValidationError1,
form.getFormElem().find(emailFieldSelector)
);
form.submittable(false);
}
else {
form.submittable(form.submittable() !== false);
}
});
form.onSubmit(function(form) {
});
});

</script>

Outcomes