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

Validation of an email address is one of the common operations one does when processing a form.

电子邮件地址的验证是处理表单时的常见操作之一。

It’s useful in contact forms, signup and login forms, and much more.

在联系表格,注册和登录表格等中很有用。

Some people suggest that you should not validate emails at all. I think a little bit of validation, without trying to be over-zealous, is better.

有人建议您完全不要验证电子邮件 。 我认为稍微验证一下会更好,但不要太过热情。

电子邮件验证应遵循哪些规则? (What are the rules that email validation should follow?)

An email address is composed by 2 parts the local part, and the domain part.

电子邮件地址由本地部分和域部分两部分组成。

The local part can contain

本地部分可以包含

  • any alphanumeric character: a-zA-Z0-9

    任何字母数字字符: a-zA-Z0-9

  • punctuation: "(),:;<>@[\]

    标点符号: "(),:;<>@[\]

  • special characters: !#$%&'*+-/=?^_{|}~

    特殊字符: !#$%&'*+-/=?^_ {|}~

  • a dot ., if it’s not the first or last character. Also, it can’t be repeated

    一个点. ,如果不是第一个或最后一个字符。 另外,它不能重复

The domain part can contain

域部分可以包含

  • any alphanumeric character: a-zA-Z0-9

    任何字母数字字符: a-zA-Z0-9

  • the hyphen -, if it’s not the first or last character. It can be repeated

    连字符- ,如果不是第一个或最后一个字符。 可以重复

使用正则表达式 (Use a Regex)

The best option to validate an email address is by using a Regular Expression.

验证电子邮件地址的最佳选择是使用正则表达式

There is no universal email check regex. Everyone seems to use a different one, and most of the regex you find online will fail the most basic email scenarios, due to inaccuracy or to the fact that they do not calculate the newer domains introduced, or internationalized email addresses

没有通用的电子邮件检查正则表达式。 每个人似乎使用的都是不同的,由于不准确或由于他们不计算引入的较新域或国际化的电子邮件地址,因此您在网上找到的大多数正则表达式将无法通过最基本的电子邮件方案

Don’t use any regular expression blindly, but check it first.

不要盲目使用任何正则表达式,而是先检查一下。

I made this example on Glitch that will check a list of email addresses considered valid against a regex. You can change the regex and compare it with other ones you want to use.

在Glitch上创建此示例,该示例将检查对正则表达式有效的电子邮件地址列表。 您可以更改正则表达式,并将其与您要使用的其他正则表达式进行比较。

The one that’s currently added is the one I consider the most accurate I found, slightly edited to fix an issue with multiple dots.

目前添加的是我认为最准确的一个,对其进行了稍微编辑以修正带有多个点的问题。

Note: I did not came up with it. I found it in a Quora answer but I am not sure that was the original source.

注意:我没有提出。 我在Quora答案中找到了它,但是我不确定那是原始来源。

This is a function that validates using that regex:

此函数可使用该正则表达式进行验证:

const validate = (email) => {
  const expression = /(?!.*\.{2})^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i

  return expression.test(String(email).toLowerCase())
}

All the common cases are satisfied, one can assume that 99.9% of the email addresses people will add are validated successfully.

满足所有常见情况,可以假设人们将添加的99.9%的电子邮件地址已成功验证。

The code of this glitch contains other regular expressions that you can easily try by remixing the project.

该故障代码包含其他正则表达式,您可以通过重新混合项目轻松地尝试这些正则表达式。

Although pretty accurate, there are a couple issues with some edge cases with this regex, which you can live with (or not) depending on your needs.

尽管非常准确,但是此正则表达式在一些极端情况下存在一些问题,您可以根据需要使用(或不使用)这些正则表达式。

False negative for weird addresses like

错误的否定,例如奇怪的地址

"very.(),:;<>[]".VERY."very@\ "very".unusual"@strange.example.com

one."more\ long"@example.website.place

False negative for local addresses:

本地地址的假否定:

admin@mailserver1
user@localserver

of little use in publicly accessible websites (actually a plus in publicly accessible websites to have those denied)

在可公开访问的网站中使用很少(实际上,在可公开访问的网站中被拒绝的网站加号)

Also, false negative for IP-based emails:

此外,对于基于IP的电子邮件,为假阴性:

user@[2001:DB8::1]
user@128.0.0.1

There is a false positive for addresses with the local part too long:

对于本地部分时间过长的地址,存在误报:

1234567890123456789012345678901234567890123456789012345678901234+x@example.com

您想要更简单的正则表达式吗? (Do you want a simpler regex?)

The above regex is very complicated, to the point I won’t even try to understand it. Regular expressions masters created it, and it spread through the Internet until I found it.

上面的正则表达式非常复杂,以至于我什至不会尝试理解它。 正则表达式大师创建了它,并在Internet上传播,直到我找到它为止。

Using it at this point is a matter of copy/pasting it.

此时使用它只是复制/粘贴它。

A much simpler solution is just to check that the address entered contains something, then an @ symbol, and then something else.

一个简单得多的解决方案是检查输入的地址是否包含某些内容,然后是@符号,然后是其他内容。

In this case, this regex will do the trick:

在这种情况下,此正则表达式可以解决问题:

const expression = /\S+@\S+/
expression.test(String('my-email@test.com').toLowerCase())

This will cause many false positives, but after all the ultimate test on an email address validity happens when you ask the user to click something in the email to confirm the address, and I’d rather try to send to an invalid email than reject a valid email because of an error in my regex.

这将导致许多误报,但是在您要求用户单击电子邮件中的某些内容以确认地址时对电子邮件地址的有效性进行最终测试之后,我宁愿尝试发送给无效的电子邮件,也不要拒绝由于我的正则表达式中存在错误,因此电子邮件有效。

This is listed in the above Glitch, so you can easily try it.

这在上面的小故障中已列出,因此您可以轻松尝试。

直接验证HTML字段 (Validate the HTML field directly)

HTML5 provided us the email field type, so don’t forget you can also validate emails using that:

HTML5为我们提供了email字段类型,所以请不要忘记您也可以使用以下方法来验证电子邮件:

<input type="email" name="email" placeholder="Your email" />

Depending on the browser implementation also this validation will give you different results.

根据浏览器的实施方式,此验证也会为您提供不同的结果。

This Glitch shows the same emails I tested the regex with, and their result when validated through the HTML form.

这个故障显示了与我测试正则表达式相同的电子邮件,以及通过HTML表单验证后的结果。

The results are interesting, and here as well we have invalid emails that pass, and valid emails that don’t. Our regex actually does a more accurate job than the HTML filtering built into the browser.

结果很有趣,在这里,我们还有通过的无效电子邮件和没有通过的有效电子邮件。 实际上,我们的正则表达式比浏览器内置HTML过滤功能更准确。

验证服务器端 (Validate server-side)

If your app has a server, the server needs to validate the email as well, because you can never trust client code, and also JavaScript might be disabled on the user browser.

如果您的应用程序具有服务器,则服务器也需要验证电子邮件,因为您永远无法信任客户端代码,并且用户浏览器上JavaScript可能已禁用。

Using Node.js you have the advantage of being able to reuse the frontend code as-is. In this case the function that validates can work both client-side and server-side.

使用Node.js,您可以直接重用前端代码。 在这种情况下,验证功能可以同时在客户端和服务器端工作。

You can also use pre-made packages like isemail, but also in this case results vary. Here is the isemail benchmark on the same emails we used above: https://glitch.com/edit/#!/flavio-email-validation-node-isemail

您还可以使用像isemail这样的预制软件包,但在这种情况下,结果也会有所不同。 这是我们上面使用的相同电子邮件的isemail基准: https ://glitch.com/edit/#!/flavio-email-validation-node-isemail

翻译自: https://flaviocopes.com/how-to-validate-email-address-javascript/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
教你怎么正确使用邮箱地址验证代码 下面是一些常用的正则表达式: 匹配文字符的正则表达式: [\u4e00-\u9fa5] 评注:匹配文还真是个头疼的事,有了这个表达式就好办了 匹配双字节字符(包括汉字在内):[^\x00-\xff] 评注:可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1) 匹配空白行的正则表达式:\n\s*\r 评注:可以用来删除空白行 匹配HTML标记的正则表达式:<(\S*?)[^>]*>.*?</\1>|<.*? /> 评注:网上流传的版本太糟糕,上面这个也仅仅能匹配部分,对于复杂的嵌套标记依旧无能为力 匹配首尾空白字符的正则表达式:^\s*|\s*$ 评注:可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式 匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* 评注:表单验证时很实用 匹配网址URL的正则表达式:[a-zA-z]+://[^\s]* 评注:网上流传的版本功能很有限,上面这个基本可以满足需求 匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$ 评注:表单验证时很实用 匹配国内电话号码:\d{3}-\d{8}|\d{4}-\d{7} 评注:匹配形式如 0511-4405222 或 021-87888822 匹配腾讯QQ号:[1-9][0-9]{4,} 评注:腾讯QQ号从10000开始 匹配国邮政编码:[1-9]\d{5}(?!\d) 评注:国邮政编码为6位数字 匹配身份证:\d{15}|\d{18} 评注:国的身份证为15位或18位 匹配ip地址:\d+\.\d+\.\d+\.\d+ 评注:提取ip地址时有用 匹配特定数字: ^[1-9]\d*$ //匹配正整数 ^-[1-9]\d*$ //匹配负整数 ^-?[1-9]\d*$ //匹配整数 ^[1-9]\d*|0$ //匹配非负整数(正整数 + 0) ^-[1-9]\d*|0$ //匹配非正整数(负整数 + 0) ^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$ //匹配正浮点数 ^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$ //匹配负浮点数 ^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$ //匹配浮点数 ^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$ //匹配非负浮点数(正浮点数 + 0) ^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$ //匹配非正浮点数(负浮点数 + 0) 评注:处理大量数据时有用,具体应用时注意修正 匹配特定字符串: ^[A-Za-z]+$ //匹配由26个英文字母组成的字符串 ^[A-Z]+$ //匹配由26个英文字母的大写组成的字符串 ^[a-z]+$ //匹配由26个英文字母的小写组成的字符串 ^[A-Za-z0-9]+$ //匹配由数字和26个英文字母组成的字符串 ^\w+$ //匹配由数字、26个英文字母或者下划线组成的字符串
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值