正则表达式,用于验证美国电话号码格式 [英] RegEx for validating US phone number format

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

问题描述

我搜索了电话号码验证并以下面的javascript代码结尾

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
      phone_number = phone_number.replace(/\s+/g, "");
      return this.optional(element) || phone_number.length > 9 &&
               phone_number.match(/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/);
}, "");

对于以下格式,上面的代码将返回true

123-123-1234 (123)123-1234 1231231234

我需要添加数字的扩展名,例如

123-123-1234 x1234

(123)123-1234 x1234

1231231234 x1234

我尝试过使用正则表达式的全部经验(很少:)),但没有用:(

您可以更改我的正则表达式以验证 x1234

谢谢.

解决方案

您可以在正则表达式的末尾添加可选的匹配项

( x\d{4})? 

x后面将匹配数字,例如x1234(如果存在)

  • ( x\d{4})?量词?匹配( x\d{4})的零个或一次出现

    正则表达式可以是

    ^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})( x\d{4})?$
    

    例如: http://regex101.com/r/sG9qJ6/1

    I searched for phone number validation and ended up with below javascript code

    jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
          phone_number = phone_number.replace(/\s+/g, "");
          return this.optional(element) || phone_number.length > 9 &&
                   phone_number.match(/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/);
    }, "");
    

    The above code will return true for below formats

    123-123-1234 or (123) 123-1234 or 1231231234

    Nw I need to add extension for number for eg

    123-123-1234 x1234

    (123) 123-1234 x1234

    1231231234 x1234

    I tried with all my experience with regex (much little :) ) but didn't worked :(

    Can you change in my regex to validate x1234

    Thanks.

    解决方案

    You can add an optional match at the end of the regex

    ( x\d{4})? 
    

    Which will match x followed by digits, that is eg x1234 if it is present

    • ( x\d{4})? the quantifier ? matches zero or one occurence of ( x\d{4})

    The regex can be

    ^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})( x\d{4})?$
    

    For example : http://regex101.com/r/sG9qJ6/1

    这篇关于正则表达式,用于验证美国电话号码格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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