简体   繁体   English

电子邮件验证Javascript RegExp

[英]Email validation Javascript RegExp

With this RegExp I can easily check if an email is valid or not: 借助此RegExp,我可以轻松检查电子邮件是否有效:

RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);

However, this just return true for such addresses: 但是,对于这样的地址,这只是返回true:

example@example.com

I also want to accept: 我也想接受:

*@example.com

What changes I need to apply on my RegExp? 我需要对RegExp应用哪些更改?

Thanks in advance 提前致谢

To answer your question literally, you can "augment" your regex: 要从字面上回答您的问题,您可以“增强”您的正则表达式:

RegExp(/^([\w.*-]+@([\w-]+\.)+[\w-]{2,4})?$/);

But this is a terrible regex for e-mail validation. 但这是用于电子邮件验证的可怕正则表达式。 Regex is the wrong tool for this. 正则表达式是错误的工具 Why do you insist on doing it this way ? 您为什么坚持要这样做呢

Checking email addresses is not that straightforward, cf. 检查电子邮件地址不是那么简单,请参阅。 RFC 822, sec 6.1 . RFC 822,秒6.1

A good list of regexes can be found at http://www.regular-expressions.info/email.html , describing tradeoffs between RFC conformance and practicality. 可以在http://www.regular-expressions.info/email.html上找到大量的正则表达式,描述了RFC一致性和实用性之间的折衷。

A couple of things: to accept *@foo.bar : 有两件事:接受*@foo.bar

var expression = /^([\w-\.*]+@([\w-]+\.)+[\w-]{2,4})?$/;//no need to pass it to the RegExp constructor

But this expression does accept -@-.-- , but then again, regex and email aren't all too good a friends. 但是此表达式确实接受-@-.-- ,但是正则表达式和电子邮件并不是一个很好的朋友。 But based on your expression, here's a slightly less unreliable version: 但是根据您的表情,这是一个不太可靠的版本:

var expression = /^[\w-\.\d*]+@[\w\d]+(\.\w{2,4})$/;

There is an expression that validates all valid types of email addresses, somewhere on the net, though. 不过,有一个表达式可以验证网络上某处的所有有效类型的电子邮件地址。 Look into that, to see why regex validating is almost always going to either exclude valid input or be too forgiving 研究一下,看看为什么正则表达式验证几乎总是会排除有效输入或太宽容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM