JavaScript regexp match against variable email domain

后端 未结 4 2052
执笔经年
执笔经年 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:44

    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
    }
    

提交回复
热议问题