I’m trying to create a regex for a phone number validation. The pattern should work like that: if the user writes the prefix (with the plus symbol optional), then the phone number must follow with 4 to 14 numbers. Otherwise, when the prefix is not given, the user has to write from 4 to 14 numbers only.
The regex I wrote is that:
^([+]?[0-9]{1,3})([0-9]{4,14})$|^([0-9]{4,14})$
I’ve tested the regex with these strings:
3333333333 –> works
+393333333333 –> works
+39333 –> works but it shouldn’t. I expected to have at least four numbers after the prefix
What am I missing?
2
Answers
Here’s a regular expression you can use to validate a phone number with or without a prefix:
Here are some examples of phone numbers that would match this regular expression:
+1 555-123-4567 |
555-123-4567 |
5551234567 |
1 555 123 4567
Note that this regular expression assumes that the phone number has 10 digits (without the prefix) or 13 digits (with the prefix). If you need to allow for phone numbers with a different number of digits, you may need to modify the regular expression accordingly.
You are defining "the prefix" as
[0-9]{1,3}
with a quantifier that allows backtrackingSo it can also match a single digit followed by a minimum of 4 digits in the second part
[0-9]{4,14}
which matches+39333
in total.You could make the pattern more specific, as
[0-9]{1,3}
can match any digit 1 to 3 times and you can not tell what the (valid) prefix is.For example making +39 optional:
Regex demo