0

Studying regexp in javascript. I need to make check for the entered email.

Have this:

reg=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/

But I need to check if this email ends on @google.com or @me.com. Like /@google.com$|@me.com$/. Almost break my mind. Help me please)

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
kliukovking
  • 569
  • 1
  • 5
  • 16

2 Answers2

3

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);
    }
}
Fabien
  • 4,862
  • 2
  • 19
  • 33
1

Validating e-mail addresses with a regular expression is a tricky thing. I guess if you only want to allow certain domains it simplifies things a bit. Something like could do the trick:

\w+@(google|me)\.com$

The \w+ before the @ is of course over simplified. Expand this to what you need ...

user1777136
  • 1,746
  • 14
  • 28