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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line