使用 JavaScript 验证电话号码 [英] Validate phone number with JavaScript

查看:44
本文介绍了使用 JavaScript 验证电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某个网站上找到了这段代码,它运行良好.它验证电话号码是否采用以下格式之一:
(123) 456-7890123-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.

推荐答案

首先,您的格式验证器显然只适用于 NANP(国家/地区代码 +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,即使该号码不是有效的电话号码.您可以通过将 d{3} 替换为 [2-9]{1}d{2} 来解决这个问题.

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}.

最后,我感觉您正在验证 Web 浏览器中的用户输入.请记住,客户端验证是只是您提供给的便利用户;您仍然需要(再次)验证服务器上的所有输入.

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 验证电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆