Html 带括号的电话号码的 HTML5 模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18863420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 pattern for phone number with parentheses
提问by Delmon Young
I've got an HTML5 pattern that works great for phone numbers in the following format:
我有一个 HTML5 模式,适用于以下格式的电话号码:
111-222-3333
111 222 3333
(777)-888-9999
(777)888-9999
But if a user enters
但是如果用户输入
(777-999-9999
It passes the validation. Ideally I'd want this to throw an error since the parentheses is clearly not closed. Here is my pattern:
它通过验证。理想情况下,我希望这会引发错误,因为括号显然没有关闭。这是我的模式:
pattern="^\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}$"
Any ideas on what I'm doing wrong? I've been banging my head against a wall for hours on this one. Thanks!
关于我做错了什么的任何想法?几个小时以来,我一直在用头撞墙。谢谢!
回答by Bergi
The optionalities of the two parenthesis are independent of each other. Use an alternation:
两个括号的可选性是相互独立的。使用替代:
pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}"