我想使用 Javascript 中的正则表达式验证 10 位美国风格的电话号码,然后通过 url 将其提交到 PHP 服务器。它将是一个简单的表单文本框,用于输入数字和一个提交按钮。
例如,验证后,网址可能是:
thisdomainname.com/resultspage.php?phonenumber=4392931234
我知道正则表达式是如何工作的,但对更复杂的表达式感到困惑。我在 stackoverflow 和互联网上搜索了一个解决方案,找到了几个,但没有一个完全符合我的需要和/或在我运行它时有效。
我需要它省略所有非数字字符(例如括号、破折号和句点),并省略美国 10 位数电话号码中可选的额外前导“1”。
它应该允许(验证正确)以下格式:
1-(805) xxx-xxxx
215.xxx.xxxx
但因无效而拒绝:
-
805 931 42
-
805 931 42ab
-
105 931 4288
理想情况下,它会允许根据“北美编号计划”使用电话号码,该计划具有以下规则:
"Area codes start with a number from 2–9, followed by 0–8, and then any third digit. The second group of three digits, known as the central office or exchange code, starts with a number from 2–9, followed by any two digits. The final four digits, known as the station code, have no restrictions."
我找到了一个正则表达式来实现下面的功能,但我无法让它与可选的前导“1”数字一起使用。
^\(?([2-9][0-8][0-9])\)?[-. ]?([2-9][0-9]{2})[-. ]?([0-9]{4})$
正如我所说,我已经找到了许多解决此问题的解决方案,但没有一个解决方案适用于我上面概述的所有情况。
提前致谢。
最佳答案
更简单的方法是删除所有非数字字符并确保位数有效
function isValidPhoneNumber(value) {
if (!value) return false;
var count = value.replace(/[^0-9]/g, "").length;
return count == 10 || count == 11;
}
关于php - 使用正则表达式和 javascript 验证美国电话号码并使用 php 提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18679577/