乐闻世界logo
搜索文章和话题

JS 如何验证电子邮件地址

7 个月前提问
3 个月前修改
浏览次数146

6个答案

1
2
3
4
5
6

在JavaScript中验证电子邮件地址通常涉及到检查该地址是否符合电子邮件地址的标准格式。这通常通过使用正则表达式(Regular Expressions)来完成,正则表达式是一种强大的模式匹配工具,可以用来检测字符串是否符合特定的格式。

以下是一个使用正则表达式来验证电子邮件地址的例子:

javascript
function validateEmail(email) { var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; return emailRegex.test(email); } // 使用示例 var email = "example@example.com"; if (validateEmail(email)) { console.log(email + " 是一个有效的电子邮件地址。"); } else { console.log(email + " 不是一个有效的电子邮件地址。"); }

这里的正则表达式解释如下:

  1. ^ :表示匹配字符串的开始。
  2. [a-zA-Z0-9._-]:表示可以包含小写字母a-z、大写字母A-Z、数字0-9以及点号、下划线和破折号。
  3. +:表示前面的字符或子表达式至少出现一次。
  4. @:字面量@字符,电子邮件地址的一部分。
  5. [a-zA-Z0-9.-]:表示域名部分可以包含小写字母a-z、大写字母A-Z、数字0-9以及点号和破折号。
  6. \.:转义后的点号,表示域名的部分。
  7. [a-zA-Z]{2,6}:表示顶级域名(TLD),可以是两到六个字母长。
  8. $:表示匹配字符串的结尾。

这个正则表达式仅是一个基础版本,用于匹配大部分电子邮件地址的格式。然而,电子邮件地址的规范(例如RFC 5322)要复杂得多,包含许多特殊的规则和例外,这意味着创建一个完全符合规范的正则表达式非常复杂并且会很长。因此,上述正则表达式在实际应用中可能会因为太过简化而排除一些有效的电子邮件地址,或者可能会接受一些不合规范的电子邮件地址。

此外,即使一个电子邮件地址的格式正确,也无法保证该电子邮件地址是存在的或者可以接收邮件。要验证电子邮件地址是否真正有效,您可能还需要发送一封确认邮件并要求用户点击其中的链接以验证他们的地址。

为了提高用户体验,现代web应用程序通常会在前端使用类似的正则表达式来做初步验证,然后再在后端进行进一步的检查,也可能包括发送确认邮件来验证电子邮件地址的真实性。

2024年6月29日 12:07 回复

使用正则表达式可能是在 JavaScript 中验证电子邮件地址的最佳方法。查看来自Chromium的 JSFiddle 测试

shell
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 的正则表达式示例。

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

请记住,不应单独依赖 JavaScript 验证,因为 JavaScript 很容易被客户端禁用。此外,在服务器端进行验证也很重要。

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

shell
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>

展开片段

2024年6月29日 12:07 回复

I've slightly modified Jaymon's answer for people who want really simple validation in the form of:

shell
anystring@anystring.anystring

The regular expression:

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

To prevent matching multiple @ signs:

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

The above regexes match the whole string, remove the leading and ^ and trailing $ if you want to match anywhere in the string. The example below matches anywhere in the string.

If you do want to match the whole sring, you may want to trim() the string first.

Example JavaScript function:

shell
function validateEmail(email) { var re = /\S+@\S+\.\S+/; return re.test(email); } console.log(validateEmail('my email is anystring@anystring.any')); // true console.log(validateEmail('my email is anystring@anystring .any')); // false

Run code snippetHide results

Expand snippet

2024年6月29日 12:07 回复

Just for completeness, here you have another RFC 2822 compliant regex

The official standard is known as RFC 2822. It describes the syntax that valid email addresses must adhere to. You can (but you shouldn'tread 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 asdf@adsf.adsf. 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.

Emphasis mine

2024年6月29日 12:07 回复

Wow, there are lots of complexity here. If all you want to do is just catch the most obvious syntax errors, I would do something like this:

shell
^\S+@\S+$

It usually catches the most obvious errors that the user makes and assures that the form is mostly right, which is what JavaScript validation is all about.

EDIT: We can also check for '.' in the email using

shell
/^\S+@\S+\.\S+$/
2024年6月29日 12:07 回复

There's something you have to understand the second you decide to use a regular expression to validate emails: It's probably not a good idea. Once you have come to terms with that, there are many implementations out there that can get you halfway there, this article sums them up nicely.

In short, however, the only way to be absolutely, positively sure that what the user entered is in fact an email is to actually send an email and see what happens. Other than that it's all just guesses.

2024年6月29日 12:07 回复

你的答案