电子邮件地址正则表达式验证

时间:2019-06-07 08:22:52

标签: javascript regex string ecmascript-6

如何更新以下正则表达式/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/以在电子邮件地址中接受“ +”。

现在:

abc@gmail.com //是

abc+100@gmail.com //错误

我需要

abc@gmail.com //是

abc+100@gmail.com //是

我的代码:

export const handleEmailValidation = (email) => {
  const validEmailAddress = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
  const containAt = /^((?!@).)*$/;
  const lastAt = /^[a-z|A-Z|0-9]+[^@]\s?@{1}$/;
  if (containAt.test(String(email).toLowerCase())) {
    return 'An email address must contain a single @ ';
  }
  if (lastAt.test(String(email).toLowerCase())) {
    return 'Please enter a valid value after the @ ';
  }
  if (!validEmailAddress.test(String(email).toLowerCase())) {
    return 'Please enter a valid email address';
  }
  return '';
};

2 个答案:

答案 0 :(得分:1)

+字符添加到第一个字符集:

/^([a-zA-Z0-9_\-\.+]+)...
                  ^

答案 1 :(得分:0)

您可以仅使用以下正则表达式;

^[\w.+\-]+@gmail\.com$

[
\W -  Matches any word character (alphanumeric & underscore).
.  -  Matches a "." character.
+  -  Matches a "+" character. 
\  -  Matches a "-" character.
]
+  -  Match 1 or more of the preceding token.
@  -  Matches a "@" character. 
gmail - Matches gmail characters.
\. -  Matches a "." character.
com - Matches com characters.
$ -  Matches the end of the string.

RegExpr example

您可以添加“ i”修饰词,表示“忽略大小写”

var regex = new RegExp('^[\w.+\-]+@gmail\.com$', 'i');
console.log(regex.test("abc@gmail.com"));
console.log(regex.test('abc+100@gmail.com'));

相关问题