我试图把一个全面的正则表达式放在一起来验证电话号码。理想情况下,它可以处理国际格式,但它必须处理美国格式,包括以下内容:

1-234-567-8901 1-234-567-8901 x1234 1-234-567-8901 ext1234 1 (234) 567-8901 1.234.567.8901 1/234/567/8901 12345678901

我会用我目前的尝试来回答,但我希望有人有更好的和/或更优雅的东西。


当前回答

对这个话题的大量回复加强了我的直觉——这个问题实际上有无数个解决方案,没有一个是优雅的。

老实说,我建议你不要尝试验证电话号码。即使您可以编写一个允许所有不同合法格式的大型、复杂的验证器,它最终也会允许几乎任何东西,甚至在一开始就允许与电话号码相差甚远的东西。

在我看来,最优雅的解决方案是验证最小长度,仅此而已。

其他回答

我在另一个SO问题上回答了这个问题,然后决定把我的答案也包括在这个线程上,因为没有人解决如何要求/不要求项目,只是分发正则表达式: 正则表达式工作错误,匹配意想不到的东西

从我在那个网站上的帖子中,我创建了一个快速指南,帮助任何人为自己想要的电话号码格式制作自己的正则表达式,我要警告(就像我在另一个网站上所做的那样),如果你限制太多,你可能不会得到想要的结果,并且没有“一宜之计”的解决方案来接受世界上所有可能的电话号码——只有你决定接受的格式作为你选择的格式。使用风险自负。

快速小抄

Start the expression: /^ If you want to require a space, use: [\s] or \s If you want to require parenthesis, use: [(] and [)] . Using \( and \) is ugly and can make things confusing. If you want anything to be optional, put a ? after it If you want a hyphen, just type - or [-] . If you do not put it first or last in a series of other characters, though, you may need to escape it: \- If you want to accept different choices in a slot, put brackets around the options: [-.\s] will require a hyphen, period, or space. A question mark after the last bracket will make all of those optional for that slot. \d{3} : Requires a 3-digit number: 000-999. Shorthand for [0-9][0-9][0-9]. [2-9] : Requires a digit 2-9 for that slot. (\+|1\s)? : Accept a "plus" or a 1 and a space (pipe character, |, is "or"), and make it optional. The "plus" sign must be escaped. If you want specific numbers to match a slot, enter them: [246] will require a 2, 4, or 6. (?:77|78) or [77|78] will require 77 or 78. $/ : End the expression

我尝试使用一个无限制的正则表达式:

/^[+#*\(\)\[\]]*([0-9][ ext+-pw#*\(\)\[\]]*){6,45}$/

接受:

+(01) 123 (456) 789 ext555
123456
*44 123-456-789 [321]
123456
123456789012345678901234567890123456789012345
*****++[](][((( 123456tteexxttppww

拒绝:

mob 07777 777777
1234 567 890 after 5pm
john smith
(empty)
1234567890123456789012345678901234567890123456
911

它是由你来消毒展示。经过验证,它可能是一个数字。

简单的正则表达式和其他技巧都有用。

.*

但是显示输入的提示/示例/占位符/工具提示。

然后在提交之前在前端验证格式是否正确是最好的体验。

这将为没有经验的用户简化格式。

这是一个简单的菲律宾手机号码的正则表达式模式:

((\+[0-9]{2})|0)[.\- ]?9[0-9]{2}[.\- ]?[0-9]{3}[.\- ]?[0-9]{4}

or

((\+63)|0)[.\- ]?9[0-9]{2}[.\- ]?[0-9]{3}[.\- ]?[0-9]{4}

将匹配这些:

+63.917.123.4567  
+63-917-123-4567  
+63 917 123 4567  
+639171234567  
09171234567  

第一个将匹配任何两位数的国家代码,而第二个将匹配菲律宾国家代码。

在这里测试:http://refiddle.com/1ox

既然写电话号码有很多选择, 我们可以测试其中有足够的数字,不管它们是如何分开的。我发现9到14个数字适合我:

^\D*(\d\D*){9,14}$

正确的:

123456789 1234567890123 +123 (456) 78.90-98.76

错误的:

123 (1234) 1234 9007199254740991 我不会按你说的去做 +123 (456) 78.90-98.76 #543 ext 210>2>5>3 早上打456-7890 18:00后打987 - 54-3210找雪莉

如果你想支持最后两个例子,只需要移除上限:

(\d\D*){9,}

(如果没有上限,则不需要^$)