doupo5861 2013-09-08 01:35
浏览 107

使用正则表达式和javascript验证美国电话号码并使用php提交[关闭]

I want to validate a 10 digit USA style phone number using a Regular Expression in Javascript and then submit it to the PHP server via the url. It will be a simple text box in a form for typing in the number and a button to submit.

For example, after validation, the url might be:

thisdomainname.com/resultspage.php?phonenumber=4392931234

I know how regular expressions work but am confused by more complex ones. I have searched stackoverflow and the internet for a solution and found several but none that fits what I need exactly and/or works when I run it.

I need it to omit all non numeric characters (such as parens, dashes and periods), and also omit the extra leading "1" that is optional in USA 10 digit phone numbers.

It should allow (validate as correct) the following formats:

  • 1-(805) xxx-xxxx

  • 215.xxx.xxxx

But reject as invalid:

  • 805 931 42
  • 805 931 42ab
  • 105 931 4288

Ideally it would allow phone numbers according to the "North American Numbering Plan," which has the following rules:

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

I found a regex to implement this below, but I can't get it to work with the optional leading "1" digit.

^\(?([2-9][0-8][0-9])\)?[-. ]?([2-9][0-9]{2})[-. ]?([0-9]{4})$

Like I say, I have found many solutions addressing this problem in general, but none that will work with all the situations I've outlined above.

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • douyun6399 2013-09-08 02:25
    关注

    A simpler approach is just to remove all non-digit characters and make sure the number of digits is valid

    function isValidPhoneNumber(value) {
        if (!value) return false;
        var count = value.replace(/[^0-9]/g, "").length;
    
        return count == 10 || count == 11;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图