Валидация номера телефона php

In this short tutorial, we’re going to look at validating a phone number in PHP. Phone numbers come in many formats depending on the locale of the user. To cater for international users, we’ll have to validate against many different formats.

In this article

  • Validating for Digits Only
  • Checking for Special Characters
  • International Format
  • Key Takeaways
  • 10 minute read

Validating for Digits Only

Let’s start with a basic PHP function to validate whether our input telephone number is digits only. We can then use our isDigits function to further refine our phone number validation.

We use the PHP preg_match function to validate the given telephone number using the regular expression:

/^[0-9]{'.$minDigits.','.$maxDigits.'}z/

This regular expression checks that the string $s parameter only contains digits [0-9] and has a minimum length $minDigits and a maximum length $maxDigits. You can find detailed information about the preg_match function in the PHP manual.

Checking for Special Characters

Next, we can check for special characters to cater for telephone numbers containing periods, spaces, hyphens and brackets .-(). This will cater for telephone numbers like:

  • (012) 345 6789
  • 987-654-3210
  • 012.345.6789
  • 987 654 3210

The function isValidTelephoneNumber removes the special characters .-() then checks if we are left with digits only that has a minimum and maximum count of digits.

International Format

Our final validation is to cater for phone numbers in international format. We’ll update our isValidTelephoneNumber function to look for the + symbol. Our updated function will cater for numbers like:

  • +012 345 6789
  • +987-654-3210
  • +012.345.6789
  • +987 654 3210

The regular expression:

/^[+][0-9]/

tests whether the given telephone number starts with + and is followed by any digit [0-9]. If it passes that condition, we remove the + symbol and continue with the function as before.

Our final step is to normalize our telephone numbers so we can save all of them in the same format.

Key Takeaways

  • Our code validates telephone numbers is various formats: numbers with spaces, hyphens and dots. We also considered numbers in international format.
  • The validation code is lenient i.e: numbers with extra punctuation like 012.345-6789 will pass validation.
  • Our normalize function removes extra punctuation but wont add a + symbol to our number if it doesn’t have it.
  • You could update the validation function to be strict and update the normalize function to add the + symbol if desired.

Проверка данных регулярными выражениями

Сборник регулярных выражений с примерами на PHP для проверки данных из полей форм.

1

Проверка чисел

$text = '1';
if (preg_match("/^d+$/", $text)) {
	echo 'yes';
} else {
	echo 'no';
}

PHP

Числа с плавающей точкой (разделитель точка):

$text = '-1.0';
if (preg_match("/^-?d+(.d{0,})?$/", $text)) {
	echo 'yes';
} else {
	echo 'no';
}

PHP

2

Проверка даты по формату

Формат DD.MM.YYYY

$text = '02.12.2018';
if (preg_match("/^(0[1-9]|[12][0-9]|3[01])[.](0[1-9]|1[012])[.](19|20)dd$/", $text)) {
	echo 'yes';
} else {
	echo 'no';
}

PHP

Формат MySQL YYYY-MM-DD

$text = '2018-04-02';
if (preg_match("/^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])$/", $text)) {
	echo 'yes';
} else {
	echo 'no';
}

PHP

3

Проверка номера телефона

Ориентировано на российские мобильные + городские с кодом из 3 цифр.

$text = '+7(495)000-00-00';
if (preg_match("/^((8|+7)[- ]?)?((?d{3})?[- ]?)?[d- ]{7,10}$/", $text)) {
	echo 'yes';
} else {
	echo 'no';
}

PHP

4

Проверка E-mail

$text = 'mail@snipp.ru';
if (preg_match("/^([a-z0-9_-]+.)*[a-z0-9_-]+@[a-z0-9_-]+(.[a-z0-9_-]+)*.[a-z]{2,6}$/i", $text)) {
	echo 'yes';
} else {
	echo 'no';
}

PHP

5

Логин

Латинские буквы, цифры, - и _.

$text = 'admin-1';
if (preg_match("/^[a-z0-9_-]{2,20}$/i", $text)) {
	echo 'yes';
} else {
	echo 'no';
}

PHP

6

Проверка md5-хэша

$text = 'ca040cb5d6c2ba8909417ef6b8810e2e';
if (preg_match("/^[a-f0-9]{32}$/", $text)) {
	echo 'yes';
} else {
	echo 'no';
}

PHP

7

Цвета

Шестнадцатеричные коды цветов #FFF и #FFFFFF.

$text = '#fff';
if (preg_match("/^#(?:(?:[a-fd]{3}){1,2})$/i", $text)) {
	echo 'yes';
} else {
	echo 'no';
}

PHP

8

IP адреса

IPv4 адрес:

$text = '192.168.0.1';
if (preg_match("/^((25[0-5]|2[0-4]d|[01]?dd?).){3}(25[0-5]|2[0-4]d|[01]?dd?)$/", $text)) {
	echo 'yes';
} else {
	echo 'no';
}

PHP

IPv6 адрес:

$text = '2001:DB8:3C4D:7777:260:3EFF:FE15:9501';
if (preg_match("/((^|:)([0-9a-fA-F]{0,4})){1,8}$/i", $text)) {
	echo 'yes';
} else {
	echo 'no';
}

PHP

14.06.2018, обновлено 21.12.2022

Другие публикации

Маски ввода для текстовых полей

Применение масок ввода у полей форм значительно упрощает их использование, уменьшает количество ошибок и приводит…

date() – форматирование даты PHP

date($format, $timestamp) – форматирует дату/время по шаблону, где…

Генерация случайных буквенно-цифровых кодов в PHP

Несколько примеров, как сгенерировать случайные последовательности численных и буквенных строк заданной длины и…

Работа с FTP в PHP

Протокол FTP – предназначен для передачи файлов на удаленный хост. В PHP функции для работы с FTP как правило всегда доступны и не требуется установка дополнительного расширения.

Виртуальные коды клавиш (Virtual-Key Codes)

В следующей таблице приведены имена констант (VK Codes), десятичные и шестнадцатеричные значения для кодов виртуальных…

Загрузка файлов на сервер PHP

В статье приведен пример формы и php-скрипта для безопасной загрузки файлов на сервер, возможные ошибки и рекомендации при работе с данной темой.

  1. Use regex Regular Expression to Validate Phone Numbers in PHP
  2. Use the filter Method to Validate Phone Numbers in PHP

Validate Phone Number in PHP

PHP has two ways to validate phone numbers, one is the regular expression regex, and the other is the filter method. We can set a template and validate phone numbers according to that template with regex, but filter will only exclude unwanted characters.

This tutorial demonstrates how to validate different phone numbers in PHP.

Use regex Regular Expression to Validate Phone Numbers in PHP

The preg_match() is a built-in function in PHP that checks if the data is according to the given format; it returns a Boolean value.

Example:

<?php
function validate_number($phone_number){
if(preg_match('/^[0-9]{11}+$/', $phone_number)) {
    // the format /^[0-9]{11}+$/ will check for phone number with 11 digits and only numbers
    echo "Phone Number is Valid <br>";
}   else{
    echo "Enter Phone Number with correct format <br>";
    }
}
//valid phone number with 11 digits
validate_number("03333333333");
//Invalid phone number with 13 digits
validate_number("0333333333333");
// 11 digits number with invalid charachters.
validate_number("03333333-33");
?>

The code above will only validate a phone number with 11 digits only.

Output:

Phone Number is Valid
Enter Phone Number with correct format
Enter Phone Number with correct format

The next example shows how to validate a phone number that begins with a - and includes special characters and country codes.

Example:

<?php
function validate_number($phone_number){
if(preg_match('/^[0-9]{4}-[0-9]{7}$/', $phone_number)){
    // the format /^[0-9]{4}-[0-9]{7}$/ will check for phone number with 11 digits with a - after first 4 digits.
    echo "Phone Number is Valid <br>";
}   else{
    echo "Enter Phone Number with correct format <br>";
   }
}
//Valid phone number with 11 digits and a -
validate_number("0333-3333333");
//Invalid phone number with 13 digits and -
validate_number("0333-333333333");
//Invaild  11 digits number with two -.
validate_number("0333-3333-33");
echo "<br>";

function validate_country_number($phone_number){
if(preg_match('/^+[0-9]{1,2}-[0-9]{3}-[0-9]{7}$/', $phone_number)){
    // the format /^+[0-9]{1,2}-[0-9]{3}-[0-9]{7}$/ will check for phone number with country codes, 11 or 12 digits, + and -
    echo "Phone Number is Valid with country code <br>";
}   else{
    echo "Enter Phone Number with correct format <br>";
   }
}
//Valid phone number with 12 digits + and -. According to the format given in the function for country code.
validate_country_number("+92-333-3333333");
//Invalid phone number with with country code
validate_country_number("+92-333333333333");
//Invaild  Number without country code.
validate_country_number("03333333333");
?>

Output:

Phone Number is Valid
Enter Phone Number with correct format
Enter Phone Number with correct format

Phone Number is Valid with country code
Enter Phone Number with correct format
Enter Phone Number with correct format

It should be mentioned here every country has its format of phone numbers. Any format can be set preg_match regex function to validate a phone number.

Use the filter Method to Validate Phone Numbers in PHP

Filters in PHP are used to validate and sanitize the data inputs. Filters also correct the format and output the correct phone number.

Example:

<?php
function validate_number($phone_number){
$valid_phone_number = filter_var($phone_number, FILTER_SANITIZE_NUMBER_INT);
echo $valid_phone_number."<br>";
}
//valid phone numbers
validate_number("03333333333");
validate_number("0333-3333333");
validate_number("+92-333-3333333");
//invalid phone numbers
validate_number("03333333&333");
validate_number("0333-33*33333");
validate_number("+92-333-333##3333");
?>

The code above uses the built-in function filter_var with the constant FILTER_SANITIZE_NUMBER_INT, which will check for integers with + and - signs. If it detects any other characters, it will exclude them and return the correct phone number.

Output:

03333333333
0333-3333333
+92-333-3333333
03333333333
0333-3333333
+92-333-3333333

The back draws of this method are we cannot set a length for a phone number, and if the + and - are at the wrong places in the number, it will not correct them. The filter method can be used when we mistakenly enter other characters, excluding them.

Phone Number Validation in PHP

PHP is a very popular server-side programming language. One of the obvious task for a server-side programming language is to process forms. Forms are used to get data from website users. You could receive different inputs from what you expected due to mistakes of users. Also, hackers could use forms to access to your internal data. Hence, it is very important to validate user input data before using them for various purposes.

Phone numbers are an essential input field in many forms. There are two ways that you can use to validate the phone numbers in PHP. you can either use PHP inbuilt filters or regular expressions for that purpose.

Phone numbers are different from country to country. When you are creating a web application that will be used by people around the globe, you have to write codes which verify each of these requirements.

You might like this :

  • Using AngularJS forEach() Function in AngularJS with Example

Phone Number Validation in PHP

Using inbuilt PHP filters easier. But, as there are different types of formats for phone numbers, you have to use regular expressions to validate these phone numbers. PHP provides you with several very powerful functions for parsing regular expressions.

Anyway, we will discuss both methods in this tutorial. First, we will study PHP filters.

Validating Phone Numbers with Filters

We don’t know what will user enter in the input fields. There are some certain characters that we can expect in a phone number.

Those are digits, ‘-’, ‘.’ and ‘+’. User sometimes could enter any other characters by mistake or with malicious intention.

We must remove those characters before doing any processing. PHP has built-in functions for this purpose. We call it sanitizing.

It will strip off any invalid characters in phone numbers.

This is how you going to do it.

function validating($phone){

$valid_number = filter_var($phone,FILTER_SANITIZE_NUMBER_INT);

echo $valid_number."<br>";

}

You can see that we have used the filter_var function with a  FILTER_SANITIZE_NUMBER_INT  constant.

Let’s try this out with few phone numbers.

function validating($phone){

$valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);

echo $valid_number."<br>";

}

validating("202$555*0170");

Output

2025550170

Great!.

It strips off the `$` sign and `*` sign and returns only digits. Sometimes you may want to allow `-` in phone numbers. For example, 202-555-0170 is a valid phone number. Let’s see how `filter_var` function reacting to it.

function validating($phone){

$valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);

echo $valid_number."<br>";

}

validating("202-555-0170");

Output

202-555-0170

Great again! We get exactly what we want. `filter_var` with `FILTER_SANITIZE_NUMBER_INT` There is one more thing. In international formatting, you need to allow + sign with country code. We have to see does filter_var supports `+` sign.

Let’s take +1-202-555-0170 and see what output does filter_var gives to it.

function validating($phone){

$valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);

echo $valid_number."<br>";

}

validating("+1-202-555-0170");

Output

+1-202-555-0170

Excellent.

There is still a small issue. We did not check the lengths of phone numbers yet.

Let’s check the number `2025550170000`.

function validating($phone){

$valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);

echo $valid_number."<br>";

}

validating("2025550170000");

Output

2025550170000

Well, filter_var is not able to validate the length of a phone number. You may want to validate it manually. You can see that the length of a phone number which includes country code could be between 10 and 14. Of course, this length is only valid if we remove ‘-’ in numbers. Let’s do it.

function validating($phone){

$valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);

$valid_number = str_replace("-", "", $valid_number);

if (strlen($valid_number) < 10 || strlen($valid_number) > 14) {

echo "Invalid Number <br>";

} else {

echo "Valid Number <br>";

}

}

validating("+1-202-555-0170000");

Output

Invalid Number

That is our final code. It gives us the expected results. Next, we will see how do we validate phone numbers using Regular Expressions

Validating Phone Numbers with Regular Expressions

A lot of beginner level developers find regular expression is difficult. Well, actually learning regular expressions is easy. Using it requires good reasoning and logic. It gives great flexibility and power to developers. Therefore, Regular Expressions are such an important tool for any developer.

In the simplest form, the phone number is a 10 digits code without any other characters.

You use the following pattern to represent that. You can use `’/^[0-9]{10}+$/’` in Regular Expressions to represent that.

PHP provides the `preg_match` function to parse Regular Expressions.

Check the following code.

function validating($phone){

if(preg_match('/^[0-9]{10}+$/', $phone)) {

echo "Valid Email <br>";

}else{

echo "Invalid Email <br>";

}

}

Let’s try this out now.

We will take several valid and invalid phone numbers and see whether our new code provides us with accurate results.

function validating($phone){

if(preg_match('/^[0-9]{10}+$/', $phone)) {

echo "Valid Email <br>";

}else{

echo "Invalid Email <br>";

}

}

validating("2025550170"); //10 digits valid phone number

validating("202555017000"); //12 digits invalid phone number

validating("202$555*01"); //10 letters phone number with invalid characters

validating("202$555*0170"); //10 digits phone numbers with invalid characters

Output

Valid Email

Invalid Email

Invalid Email

Invalid Email

Great! We get results as we want it. You can see we have covered various possible inputs in the code.

Next, we will try to validate phone numbers with 202-555-0170 format to validate.

We will have to slightly change our regular expression for that.

function validating($phone){

if(preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/', $phone)) {

echo "Valid Email <br>";

}else{

echo "Invalid Email <br>";

}

}

validating("202-555-0170");

Output

Valid Email

Notice that we have our changed our regular expression to `’/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/` which will strictly look for the `000-000-0000` pattern.

Finally, let’s validate a phone number which has an international code.

Some countries have international code with one number while the other countries include two numbers in their country codes.

So you should be able to take that into account when writing your regular expression.

function validating($phone){

if(preg_match('/^+[0-9]{1,2}-[0-9]{3}-[0-9]{3}-[0-9]{4}$/', $phone)) {

echo "Valid Email <br>";

}else{

echo "Invalid Email <br>";

}

}

validating("+1-202-555-0170");

validating("+91-202-555-0170");

Output

Valid Email

Valid Email

Conclusion

You can see how powerful Regular expressions are from these examples. You can validate any phone number against any format using Regular Expressions. On top of that PHP provides a very easy way to work with them. That’s it for Phone number validation with PHP. I will meet you with another tutorial.

  • Валетудо находка телефон регистратуры
  • Валерия федорович номер телефона
  • Валерия сервис удомля телефон
  • Валерия парикмахерская петрозаводск телефон
  • Валерия мончегорск парикмахерская телефон