Skip to content Skip to sidebar Skip to footer

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-1

Solution 1:

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

Solution 2:

What you asking for wouldn't be a simple regular expression and also may be solved without any use 'em.

functionisPhoneNumberValid(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.

Solution 3:

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 e.g. -1234567890-.

Post a Comment for "Regex Javascript Phone Number Validation Min Max Length Check"