问题描述
我在某个网站上找到了这个代码,它运行得很好。它验证电话号码是以下格式之一:
(123)456-7890 或 123-456-7890
I found this code in some website, and it works perfectly. It validates that the phone number is in one of these formats:
(123) 456-7890 or 123-456-7890
问题是我的客户(我不知道为什么,也许客户端的东西)想要添加另一种格式,连续十个数字,如下所示: 1234567890 。
The problem is that my client (I don't know why, maybe client stuffs) wants to add another format, the ten numbers consecutively, something like this: 1234567890.
我正在使用这个正则表达式,
I'm using this regular expression,
/^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/
如何添加它还验证另一种格式?我对正则表达式不太满意。
How can I add that it also validates the another format? I'm not good with regular expressions.
推荐答案
首先,您的格式验证器显然只适用于(国家代码+1)号码。您的申请是否会被来自北美以外的电话号码的人使用?如果是这样,您不希望阻止这些人输入完全有效的[国际]号码。
First off, your format validator is obviously only appropriate for NANP (country code +1) numbers. Will your application be used by someone with a phone number from outside North America? If so, you don't want to prevent those people from entering a perfectly valid [international] number.
其次,您的验证不正确。 NANP号码的格式为 NXX NXX XXXX
其中 N
是数字2-9和 X
是一个数字0-9。此外,区域代码和交换可能不采用 N11
的形式(以两个结尾),以避免与特殊服务混淆,除非非地理区域代码(800,888,877,866,855,900)可能有 N11
交换。
Secondly, your validation is incorrect. NANP numbers take the form NXX NXX XXXX
where N
is a digit 2-9 and X
is a digit 0-9. Additionally, area codes and exchanges may not take the form N11
(end with two ones) to avoid confusion with special services except numbers in a non-geographic area code (800, 888, 877, 866, 855, 900) may have a N11
exchange.
因此,即使这不是有效的电话号码,您的正则表达式也会传递数字(123)123 4566。你可以用 [2-9] {1} \d {2} \d {3}
来解决这个问题。 $ c>。
So, your regex will pass the number (123) 123 4566 even though that is not a valid phone number. You can fix that by replacing \d{3}
with [2-9]{1}\d{2}
.
最后,我感觉你在网络浏览器中验证了用户输入。请记住,客户端验证是;您仍需要在服务器上验证所有输入(再次)。
Finally, I get the feeling you're validating user input in a web browser. Remember that client-side validation is only a convenience you provide to the user; you still need to validate all input (again) on the server.
TL; DR 不使用正则表达式或。使用。
TL;DR don't use a regular expression to validate complex real-world data like phone numbers or URLs. Use a specialized library.
这篇关于使用JavaScript验证电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!