Regex Javascript电话号码验证最小-最大长度检查

Regex Javascript Phone number validation min max length check

本文关键字:检查 Javascript 电话号码 验证 Regex      更新时间:2023-09-26

我想要一个非常简单的Regex,用于Javascript验证电话号码,它允许10 digits并检查包括- dash two times在内的min numbers should be 10 and max 12,例如123-123-1234

我在网上找到了一些,但没有一个为min / max length工作。

期待这里的快速反应。

谢谢!

你可以做这个

/^(?!.*-.*-.*-)(?=(?:'d{8,10}$)|(?:(?=.{9,11}$)[^-]*-[^-]*$)|(?:(?=.{10,12}$)[^-]*-[^-]*-[^-]*$)  )['d-]+$/

在Regexr 上查看

(?!...)是否定的前瞻断言

(?=...)是正向前瞻断言

^                                          # Start of the string
    (?!.*-.*-.*-)                          # Fails if there are more than 2 dashes
    (?=(?:'d{8,10}$)                   # if only digits to the end, then length 8 to 10
        |(?:(?=.{9,11}$)[^-]*-[^-]*$)  # if one dash, then length from 9 to 11
        |(?:(?=.{10,12}$)
            [^-]*-[^-]*-[^-]*$         # if two dashes, then length from 10 to 12
         )
    )
['d-]+                                     # match digits and dashes (your rules are done by the assertions)
$                                          # the end of the string

您要的不是一个简单的正则表达式,也可以在不使用'em的情况下解决。

function isPhoneNumberValid(number){
  var parts, len = (
    parts = /^'d['d-]+'d$/g.test(number) && number.split('-'),
    parts.length==3 && parts.join('').length
  );
  return (len>=10 && len<=12)
}

当然,这可能比使用编译后的正则表达式慢一点,但如果你不打算以这种方式检查数十万个电话号码,那么开销就很小了。

这在任何方面都不完美,但可能符合您的需求,但请注意,这允许在除数字开头和结尾之外的任何位置使用两个破折号,因此这将为类似111--123123的字符串返回true

使用regexp没有简单的方法可以做到这一点,尤其是如果允许破折号出现在某些不同的点上。

如果像您的例子中那样只允许在某些地方使用破折号,那么它将是^'d{3}-?'d{3}-?'d{4}$

这个:^['d-]{10,12}$匹配长度从10到12的字符串,并且只包含数字和破折号,但它也将匹配例如-1234567890-