【问题标题】:Validating phone number in ruby在 ruby​​ 中验证电话号码
【发布时间】:2012-06-06 14:30:23
【问题描述】:

验证北美电话号码的规则是什么?另外,我可以使用regex 吗?有没有宝石可以做到这一点?

以下是我想到的几条规则

  1. 10 位数字
  2. 没有特殊字符
  3. 一个正数

【问题讨论】:

标签: ruby regex phone-number


【解决方案1】:

试试这个

(?:\+?|\b)[0-9]{10}\b

说明

@"
(?:         # Match the regular expression below
               # Match either the regular expression below (attempting the next alternative only if this one fails)
      \+          # Match the character “+” literally
         ?           # Between zero and one times, as many times as possible, giving back as needed (greedy)
   |           # Or match regular expression number 2 below (the entire group fails if this one fails to match)
      \b          # Assert position at a word boundary
)
[0-9]       # Match a single character in the range between “0” and “9”
   {10}        # Exactly 10 times
\b          # Assert position at a word boundary
"

【讨论】:

    【解决方案2】:

    有许多宝石可以为您做到这一点。

    看看:http://rubygems.org/search?utf8=%E2%9C%93&query=phone+number

    这个看起来可以满足你的需要——它本质上实现了一个正则表达式来验证电话号码:http://rubygems.org/gems/validates_phone_number

    对于美国、加拿大(百慕大、巴哈马等以及所有 +1 号码),正则表达式还应遵循其他规则。第一个数字(+1 之后)必须是 2-9。

    完整列表见:http://en.wikipedia.org/wiki/North_American_Numbering_Plan

    【讨论】:

    • validates_phone_number gem 需要 Rails,这可能是 OP 的一个陷阱。
    • 那个 gem 允许像 911 555 1234 这样的数字,这是不正确的。
    【解决方案3】:

    我在my perl code 中用于验证 NANP 电话号码的规则来自 Doug Newell 发送到 telnum-l 邮件列表的电子邮件,我在下面复制了该邮件,稍微简化为仅考虑完整的 10 位数字:

    The number 10 digits long.  We'll call this pattern:
        ABC DEF XXXX
    
    A may not be 0 or 1.
    
    B may not be 9.
    
    A+B may not be 37 or 96.
    
    B+C may not be 11.
    
    D may not be 0 or 1.
    

    您也许可以从 libphonenumber's 元数据中提取正则表达式,但请注意,这简直是地狱。

    【讨论】:

      【解决方案4】:

      我在这里写了一个 gem:https://github.com/travisjeffery/validates_phone_number,它会做你想做的事,如果你有任何问题或问题,请告诉我。

      【讨论】:

        【解决方案5】:

        如果你想要比正则表达式更高级的东西,Twilio has an API that can do this:

        Twilio Lookup 是一个 REST API,它可以:

      • 验证电话号码是否存在
      • 格式化任何国际电话 编号纳入当地标准
      • 确定电话号码是否为单元格 电话、VOIP 或固定电话
      • 发现有关电话号码的信息 载体
      • 我还没用过!但它应该可以工作,尽管您确实需要一个(免费的)Twilio 帐户。 (此外,我不隶属于 Twilio,只是拥有一个我正在玩的免费帐户。)

        【讨论】:

          【解决方案6】:
          类Phne 默认广告 放“输入你的电话号码” re=gets.chomp 如果重新= ~/\b^([0-9]{10})$\b/ 放“有效的电话号码” 别的 提出“无效的电话号码” 结尾 结尾 结尾 obj=Phne.new 对象广告

          【讨论】:

            猜你喜欢
            • 2012-10-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-02-12
            • 2020-02-29
            相关资源
            最近更新 更多