JavaScript regexp match against variable email domain

后端 未结 4 2040
执笔经年
执笔经年 2021-01-27 05:06

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

4条回答
  •  深忆病人
    2021-01-27 05:45

    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.

提交回复
热议问题