Php проверка номера телефона на валидность

Here’s how I find valid 10-digit US phone numbers. At this point I’m assuming the user wants my content so the numbers themselves are trusted. I’m using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later

//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);

//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);

//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;

Edit: I ended up having to port this to Java, if anyone’s interested. It runs on every keystroke so I tried to keep it fairly light:

boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) { 
  //14: (###) ###-####
  //eliminate every char except 0-9
  str = str.replaceAll("[^0-9]", "");

  //remove leading 1 if it's there
  if (str.length() == 11) str = str.replaceAll("^1", "");

  isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));

Here’s how I find valid 10-digit US phone numbers. At this point I’m assuming the user wants my content so the numbers themselves are trusted. I’m using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later

//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);

//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);

//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;

Edit: I ended up having to port this to Java, if anyone’s interested. It runs on every keystroke so I tried to keep it fairly light:

boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) { 
  //14: (###) ###-####
  //eliminate every char except 0-9
  str = str.replaceAll("[^0-9]", "");

  //remove leading 1 if it's there
  if (str.length() == 11) str = str.replaceAll("^1", "");

  isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));

Here’s how I find valid 10-digit US phone numbers. At this point I’m assuming the user wants my content so the numbers themselves are trusted. I’m using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later

//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);

//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);

//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;

Edit: I ended up having to port this to Java, if anyone’s interested. It runs on every keystroke so I tried to keep it fairly light:

boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) { 
  //14: (###) ###-####
  //eliminate every char except 0-9
  str = str.replaceAll("[^0-9]", "");

  //remove leading 1 if it's there
  if (str.length() == 11) str = str.replaceAll("^1", "");

  isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));

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-скрипта для безопасной загрузки файлов на сервер, возможные ошибки и рекомендации при работе с данной темой.

Простейший способ валидации телефонных номеров на сайтах

28 July 2017, 18:47 MSK

Ещё одна раздражающая проблема многих сайтов — это когда сайт заставляет вводить тебя телефонный номер в понятном ЕМУ формате. Часто разработчики таких сайтов впридачу не удосуживаются сообщить пользователю, в каком формате сайт хочет видеть номер. Совсем клиника — когда ты видишь голое поле ввода номера, вводишь номер, жмёшь «Отправить» и получаешь сообщение типа «Телефон введён неправильно». Блин, а как правильно-то? И начинаешь перебирать разные форматы…

Сегодня рассмотрим простой способ валидации (проверки правильности ввода) телефонных номеров при условии того, что все посетители сайта — из России (или Казахстана). Российские номера телефонов начинаются с +7 и имеют далее 10 цифр. При этом, все люди привыкли вводить телефонные номера по-разному. Кто-то пишет

+79219710296,

кто-то

+7 921 971 02 96,

кто-то ставит скобки и тире:

+7 (921) 971-02-96,

кто-то пишет через восьмёрку: 89219710296, кто-то пишет просто 10 цифр: 921 971 02 96, ну и так далее. В нашем способе проверки все эти примеры будут считаться валидными, а на выходе мы будем иметь телефон в едином формате +7xxxxxxxxxx для удобного хранения номера в базе данных.

Код PHP-функции проверки телефонного номера:

function validate_russian_phone_number($tel)
{
    $tel = trim((string)$tel);
    if (!$tel) return false;
    $tel = preg_replace('#[^0-9+]+#uis', '', $tel);
    if (!preg_match('#^(?:\+?7|8|)(.*?)$#uis', $tel, $m)) return false;
    $tel = '+7' . preg_replace('#[^0-9]+#uis', '', $m[1]);
    if (!preg_match('#^\+7[0-9]{10}$#uis', $tel, $m)) return false;
    return $tel;
}

Функция принимает на входе строку с телефонным номером в произвольном формате, а возвращает либо телефонный номер в формате +7xxxxxxxxxx, либо false в случае, если номер не прошёл проверку (и об этом следует сообщить пользователю).

Спасибо за внимание. Делайте удобные сайты!

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.

Регулярное выражение. Валидация номера телефона

Как проверить номер мобильного телефона? Проверка правильности, введенного номера телефона является не сложной, но важной задачей. Если пользователь введет некорректный номер, то смс сообщение до него не дойдет.

PHP проверка сотового телефона позволяет убедится, что номер телефона содержит только цифры: без тире, пробелов, дефисов, скобок и т.д. Часто владельцы прямых номеров не вводят свой код, а он необходим для отправки смс сообщения. Не зная префикса, можно только позвонить на данный номер, но нельзя отправить смс сообщение. В частном порядке можно позвонить в службы поддержки Билайна, МТС, Мегафона и попытаться выяснить какой префикс у данного прямого номера. Операторы предоставляют данную информацию.

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

/**
 * проверка - телефон ли
 * @param $_val
 * @return bool
 */
function is_phone($_val)
{
    if (empty($_val)) {
        return false;
    }

    if (!preg_match('/^+?d{10,15}$/', $_val)) {
        return false;
    }

    if (
        (mb_substr($_val, 0, 2) == '+7' and mb_strlen($_val) != 12) ||
        (mb_substr($_val, 0, 1) == '7'  and mb_strlen($_val) != 11) ||
        (mb_substr($_val, 0, 1) == '8'  and mb_strlen($_val) == 11) ||
        (mb_substr($_val, 0, 1) == '9'  and mb_strlen($_val) == 11)
    ) {
        return false;
    }
    return true;
}

  1. Регулярные выражения
  2. PHP
  3. примеры

Понравилась статья? Поделить с друзьями:
  • Pegasus номер телефона авиакомпания
  • Pegasus москва номер телефона
  • Pegasus airlines номер телефона россия
  • Pegas fly номер телефона
  • Pedant номер телефона