简体   繁体   中英

Regex Javascript Phone number validation min max length check

I want a very simple Regex for Javascript validation of phone number, which allows 10 digits and checks min numbers should be 10 and max 12 including - dash two times for ex. 123-123-1234

I have found some on internet, but none of them is working for min / max length .

Looking forward for quick response here.

Thanks !

You could do this

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

See it here on Regexr

(?!...) is a negative lookahead assertion

(?=...) is a positive lookahead assertion

^                                          # 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

What you asking for wouldn't be a simple regular expression and also may be solved without any use '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)
}

For sure this may be a bit slower than using a compiled regex, but overhead is way minor if you not going to check hundreds of thousandths phone numbers this way.

This isn't perfect in any way but may fit your needs, beware however that this allow two dashes in any place excluding start and end of number, so this will return true for string like 111--123123 .

There's no simple way to do this with regexp, especially if you allow dashes to appear at some different points.

If you allow dashes only at places as in your example, then it would be ^\\d{3}-?\\d{3}-?\\d{4}$

This one: ^[\\d-]{10,12}$ matches string with length from 10 to 12 and contains only digits and dashes, but it also will match eg -1234567890- .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM