Regex Phone validation

Asked

Viewed 3,741 times

0

I am currently using a regular expression to validate phones in the following format:

(xx) xxxxx-xxxx

It only accepts numbers that have this exact shape. I wonder how to modify the expression to accept numbers with both 9 digits (mobile), both with 8 (fixed), something like:

(xx) [x]xxxx-xxxx

Follows the expression.

/^\([0-9]{2}\) [0-9]{5}-[0-9]{4}$/
  • 1

    Change to \([0-9]{2}\) [0-9]{4,5}-[0-9]{4} only the part of [0-9]{5} for [0-9]{4,5} which instead of accepting 5 digits, will accept 4 to 5 digits. However, as mobile phones are starting with the number 9, you can do \([0-9]{2}\) 9?[0-9]{4}-[0-9]{4}, where the quantifier ? corresponds to zero or one of the literal number 9. See demo here. Unfortunately this way will validate mobile phones with 8 digits, so change to \([0-9]{2}\) (?:9[0-9]{1}|[1-5]{1})[0-9]{3}-[0-9]{4} and the demo

1 answer

0


You can use the following Regex:

/^\([0-9]{2}\) [0-9]?[0-9]{4}-[0-9]{4}$/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.