是否有 HTML5 输入电子邮件验证的 Java 实现?
我想使用新的 元素。我希望 Java 代码能够在服务器上实现与浏览器中发生的验证相同的验证。
HTML5 规范在 < 中定义了电子邮件地址 a href="https://www.rfc-editor.org/rfc/rfc5234" rel="nofollow noreferrer">ABNF 为:
1*( atext / "." ) "@" ldh-str *( "." ldh-str )
其中:
<ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
<let-dig-hyp> ::= <let-dig> | "-"
<let-dig> ::= <letter> | <digit>
<letter> ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case
<digit> ::= any one of the ten digits 0 through 9
和:
atext = ALPHA / DIGIT / ; Printable US-ASCII
"!" / "#" / ; characters not including
"$" / "%" / ; specials. Used for atoms.
"&" / "'" /
"*" / "+" /
"-" / "/" /
"=" / "?" /
"^" / "_" /
"`" / "{" /
"|" / "}" /
"~"
这些规则与 “nofollow noreferrer”>RFC 5322。 如何在 Java 中测试地址是否符合这些规则?
谢谢!
I'd like to use the new <input type="email" />
element. I'd like to have Java code that implements the same validation on the server that happens in the browser.
The HTML5 spec defines email addresses in ABNF as:
1*( atext / "." ) "@" ldh-str *( "." ldh-str )
<ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
<let-dig-hyp> ::= <let-dig> | "-"
<let-dig> ::= <letter> | <digit>
<letter> ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case
<digit> ::= any one of the ten digits 0 through 9
and:
atext = ALPHA / DIGIT / ; Printable US-ASCII
"!" / "#" / ; characters not including
"quot; / "%" / ; specials. Used for atoms.
"&" / "'" /
"*" / "+" /
"-" / "/" /
"=" / "?" /
"^" / "_" /
"`" / "{" /
"|" / "}" /
"~"
These are not the same rules as in RFC 5322.
How can I test that an address complies with these rules in Java?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用正则表达式:
You can use a regex:
实际上,W3C 建议您'vecite 提供了一个正则表达式,相当于他们所呈现的 ABNF,它定义了一个有效的电子邮件地址:
但是这个正则表达式匹配无效的电子邮件地址,例如“.any..address.@123”(用https://regex101.com/)。
此正则表达式接受(根据 Wikipedia,电子邮件地址中的所有内容均无效):
并拒绝(根据维基百科有效):
"
)请注意,W3C指出他们提出的规范是故意违规RFC 5322 的 ,所以他们有一个“借口”放弃有效的情况,但恕我直言,这不是接受无效地址的理由。
如果您不想处理这些异常情况,则可以使用 W3C 建议的正则表达式,否则,您应该使用正则表达式来涵盖您想要处理的情况。 。
Actually, The W3C Recommendation you've cited offers a regex as the equivalent for what they present as the ABNF which defines a valid email address:
But this regex matches invalid email addresses, such as ".any..address.@123" (tested with https://regex101.com/).
This regex accepts (all invalid in an email address, according to Wikipedia):
and rejects (valid according to Wikipedia):
"
)Notice that W3C states that the specification they present is a willful violation of RFC 5322, so they have an "excuse" to leave off the valid cases, but IMHO it's not a reason to accept invalid addresses.
If you won't bother with those exception cases, you can use the regex that W3C suggests. Otherwise, you should work the regex to cover the cases you want to handle.