1

I am trying to have a clientside check, if an entered value:

  • is a valid email address
  • has the right domain name

I came up with following code, but it doesn't work:

var userinput = 'dirk@something.com';
var domain = 'somethingelse.com';
domain.replace('.', '\.');
var pattern = new RegExp('/^[a-zA-Z0-9._-]+@' + domain + '$/');
if(!pattern.test(userinput))
{
    alert('not a valid email address, or the wrong domain!');
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dirk
  • 2,206
  • 4
  • 21
  • 30

4 Answers4

3

Use the split() function,

emailID.split("@")[1]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Siva Charan
  • 17,940
  • 9
  • 60
  • 95
2

Do it in two steps. First, use a regex like James recommends to test for a valid(ish) e-mail address. Second, make sure the domain matches the allowed domain as Siva suggests.

var userinput = 'dirk@something.com';
var domain = 'somethingelse.com';

var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput) || userinput.split('@')[1] != domain)
{
  alert('not a valid email address, or the wrong domain!');
}​

You can fiddle with it here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rjz
  • 16,182
  • 3
  • 36
  • 35
1

Normally I would spew out some regex here, but I think the most efficient ways of checking for email and domain are already concocted by people smarter than I.

Check How to Find or Validate an Email Address for email validation.

From that, you can limit the regex and check for a valid domain.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James L.
  • 4,032
  • 1
  • 15
  • 15
1

The argument to new RegExp() is either in /regex here/ or in quotes "regex here", but not both. The slash form generates a regex all by itself without the need for new RegExp() at all, so it's usually used only by itself and the quoted string is used with new RegExp().

var pattern = new RegExp('^[a-zA-Z0-9._-]+@' + domain + '$');

Email addresses can be a lot more complicated than you allow for here. If you really want to allow all possible legal email addresses, you will need something much more involved than this which a Google search will yield many choices.

If all you really need to do is check that the domain matches a particular domain that's a lot easier even without a regex.

var userinput = 'dirk@something.com';
var domain = 'somethingelse.com';
var testValue = "@" + domain.toLowerCase();
if (userinput.substr(userinput.length - testValue.length).toLowerCase() != testValue) {
    // Incorrect domain
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jfriend00
  • 683,504
  • 96
  • 985
  • 979