开发者问题收集

如何在 JavaScript 中验证电子邮件地址?

2008-09-05
4758432

我想在将用户输入发送到服务器或尝试向其发送电子邮件之前,用 JavaScript 检查用户输入是否为电子邮件地址,以防止最基本的输入错误。我该如何实现这一点?

3个回答

使用 正则表达式 可能是在 JavaScript 中验证电子邮件地址的最佳方法。 查看 JSFiddle 上的一系列测试 ,这些测试取自 Chromium

const validateEmail = (email) => {
  return String(email)
    .toLowerCase()
    .match(
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    );
};

以下是接受 unicode 的正则表达式的示例。

const re =
  /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

请记住,不应仅依赖 JavaScript 验证,因为客户端可以轻松禁用 JavaScript。此外,在服务器端进行验证也很重要。

以下代码片段是 JavaScript 在客户端验证电子邮件地址的示例。

const validateEmail = (email) => {
  return email.match(
    /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  );
};

const validate = () => {
  const $result = $('#result');
  const email = $('#email').val();
  $result.text('');

  if(validateEmail(email)){
    $result.text(email + ' is valid.');
    $result.css('color', 'green');
  } else{
    $result.text(email + ' is invalid.');
    $result.css('color', 'red');
  }
  return false;
}

$('#email').on('input', validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label for="email">Enter email address</label>
<input id="email" type="email">

<p id="result"></p>
2008-09-05

我稍微修改了 Jaymon 的答案 ,以便让那些想要真正简单验证的人使用以下形式:

[email protected]

正则表达式:

/^\S+@\S+\.\S+$/

为防止匹配多个 @ 符号:

/^[^\s@]+@[^\s@]+\.[^\s@]+$/

上述正则表达式匹配整个字符串,如果要在字符串中的任何位置匹配,请删除前导 ^ 和尾随 $ 。下面的示例匹配字符串中的 任何地方

如果您确实想匹配整个字符串,您可能需要先对字符串进行 trim()

示例 JavaScript 函数:

function validateEmail(email) {
  var re = /\S+@\S+\.\S+/;
  return re.test(email);
}
    
console.log(validateEmail('my email is [email protected]')); // true
    
console.log(validateEmail('my email is anystring@anystring .any')); // false
2012-02-09

为了完整性, 这里还有另一个符合 RFC 2822 的正则表达式

The official standard is known as RFC 2822 . It describes the syntax that valid email addresses must adhere to. You can ( but you shouldn't read on ) implement it with this regular expression:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

(...) We get a more practical implementation of RFC 2822 if we omit the syntax using double quotes and square brackets. It will still match 99.99% of all email addresses in actual use today.

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

A further change you could make is to allow any two-letter country code top level domain, and only specific generic top level domains. This regex filters dummy email addresses like [email protected] . You will need to update it as new top-level domains are added .

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b

So even when following official standards, there are still trade-offs to be made. Don't blindly copy regular expressions from online libraries or discussion forums. Always test them on your own data and with your own applications.

重点是我的

2009-09-03