DEV Community

Alula TYC
Alula TYC

Posted on • Edited on

PHP preg_match to validate US and Ethiopian Phone Numbers

HTML5 forms support different input types. And one of them is the number type. You can use it to force users to put in only numbers.

The problem is when you want to let your users format the phone number. For example, by letting them put dash character. In those cases, we can use the character classes and range limiters we saw above to validated formatted US and Ethiopian phone numbers like this:-

$phoneNumber = "0911-223344";
preg_match('/[0-9]{4}-[0-9]{6}/', $phoneNumber);//Simple regex to validate ethiopian phone number
preg_match("/[0-9]{3}-[0-9]{3}-[0-9]{4}/", $phoneNumber); // Simple regex to validate US phone number
Enter fullscreen mode Exit fullscreen mode

I can simplify this pattern by replacing the character class [0-9] with a simple \d. Which simply indicates any digits.

Validating Ethiopian phone number with a country code

But, what if users put dash in between numbers. Or if they start by +251, which is the country code.

To accomplish this task, we need to introduce ourselves to sub patterns.

Sub patterns enable us to group and validate a small group of our main pattern. For instance, we can group the start of our phone number to be +251 or any country code. Therefore, in our particular case we need the start to be either +251 or 09. Which, to my knowledge are the common phone number patterns Ethiopia.

Now, my pattern would start with ^+251, which means start with +251. But to match the plus sign (+) I need to escape it because + has it’s own meaning in regex. Escaping special characters is possible using the backward slash ().

Hence my start will be ^+251. Which will validate if phone numbers actuall start with +251. However, they might start with 09 too. To include that we will have to introduce ourselves to the alternate character, which is the pipe (|).

Using the pipe, the start of my phone number will be ^((+251|0)\d{3}). This will force my patterns to start with either +251 or 0 followed by a digit of size 3.

After the initial +251 or 0 followed by 3 digit numbers, we usually have a dash followed by 6 digit number. So I can do (^(+251|0)\d{3})-?\d{6}.

Note: the ? right after the dash is to indicate optional characters. That means to mean, it can appear either 0 or 1 times.

Finally our Ethiopian phone number validation regex looks like this.

$phoneNumber = "+251911-223344";
preg_match('/((^(\+251|0)\d{3})-?\d{6})/');//Simple regex to validate ethiopian phone number
Enter fullscreen mode Exit fullscreen mode

Top comments (0)