From a programming point of view, you should just start by checking if your email string terminates with @google.com
or @me.com
and only then run your regexp.
This will save you time: the regexp will be the all generic mail-format regexp you know and you can add more domains filters at any other time (put the terminating domains in an array or config...).
It also is a lot less CPU intensive. If you need to perform those checks in series and expect a lot of emails to be filtered out, then you will note an appreciable difference: dummy string comparisons are way faster than regexps.
var emails = ['jose@me.com', 'hacker@noway.com', 'hacker";DROP TABLES;@me.com' ];
var domains = ['gmail.com', 'me.com'];
function validateEmailFormat(email) {
return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)
}
function validateEmailDomain(email) {
for (i in domains) {
if (email.endsWith('@'+domains[i])) {
return true;
}
}
return false;
}
for (i in emails) {
email = emails[i];
if (validateEmailDomain(email) && validateEmailFormat(email)) {
console.log('OK for '+email);
} else {
console.log('NOT OK for '+email);
}
}