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

Validating a Phone Number in 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

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:

This regular expression checks that the string $s parameter only contains digits 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:

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:

Читайте также:  Php print function calls

tests whether the given telephone number starts with + and is followed by any digit 3 . 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.

This is the footer. If you’re reading this, it means you’ve reached the bottom of the page.
It would also imply that you’re interested in PHP, in which case, you’re in the right place.
We’d love to know what you think, so please do check back in a few days and hopefully the feedback form will be ready.

Источник

Валидация полей формы на PHP

Валидация формы на PHP

Привет, друг. Помимо того, что можно делать проверки полей формы на JavaScript, необходимо так же делать валидацию на стороне сервера и сейчас мы с вами рассмотрим пример валидации на PHP. Проверять будет такие поля, как номер телефона, email, IP адрес, адрес сайта и др. Всего полей будет 7.

Телеграм-канал serblog.ru

Валидация полей формы на PHP

Принцип действия такой: Мы делаем проверку для поля через специальные условия и если данные, введенные в это поле не проходят валидацию то под этим полем будем выводить сообщение об ошибке. И так под каждым полем. В случае, когда будут провалидированы все поля, мы отправляем форму с ее очисткой и выводим сообщение об успешной отправке. Саму форму можно посмотреть на демо странице:

Форму я сделал на Bootstrap и выглядит она так:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
form action="PHP_SELF"]);?>" method="post">< ?php echo $err['success'] ?> div class="form-group"> label for="">Имя/label> input type="text" class="form-control" name="name" value="" placeholder="Имя не более 10-ти символов"> < ?php echo $err['name'] ?> /div> div class="form-group"> label for="">Возраст/label> input type="text" class="form-control" name="num" value="" placeholder="Двузначное число"> < ?php echo $err['num'] ?> /div> div class="form-group"> label for="">Телефон/label> input type="text" class="form-control" name="phone" value="" placeholder="Номер телефона формата РФ"> < ?php echo $err['phone'] ?> /div> div class="form-group"> label for="">Email/label> input type="text" class="form-control" name="email" value="" placeholder="Emai адрес"> < ?php echo $err['email'] ?> /div> div class="form-group"> label for="">IP адрес/label> input type="text" class="form-control" name="ip" value="" placeholder="IP адрес"> < ?php echo $err['ip'] ?> /div> div class="form-group"> label for="">Сайт/label> input type="text" class="form-control" name="url" value="" placeholder="Адрес сайта"> < ?php echo $err['url'] ?> /div> div class="form-group"> label for="">Сообщение/label> textarea class="form-control" name="text" placeholder="Ваше сообщение"> < ?php echo $_POST['text'] ?> /textarea> < ?php echo $err['text'] ?> /div> button type="submit" class="btn btn-success" name="submit">Отправить/button> /form>

Вывод PHP переменно $err в HTML коде означает вывод ошибок и мы их напишем непосредственно в PHP. Я предстаавлю на ваше обозрение весь код, и уже ниже прокомментирую его.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
function clear_data($val){ $val = trim($val); $val = stripslashes($val); $val = strip_tags($val); $val = htmlspecialchars($val); return $val; } $name = clear_data($_POST['name']); $num = clear_data($_POST['num']); $phone = clear_data($_POST['phone']); $email = clear_data($_POST['email']); $ip = clear_data($_POST['ip']); $url = clear_data($_POST['url']); $text = clear_data($_POST['text']); $pattern_phone = '/^(\+7|7|8)?[\s\-]?\(?[489]9\)?[\s\-]?4[\s\-]?3[\s\-]?2$/'; $pattern_name = '/^[А-ЯЁ][а-яё]*$/'; $err = []; $flag = 0; if ($_SERVER['REQUEST_METHOD'] == 'POST'){ if (preg_match($pattern_name, $name)){ $err['name'] = ''; $flag = 1; } if (mb_strlen($name) > 10 || empty($name)){ $err['name'] = ''; $flag = 1; } if (!filter_var($num, FILTER_VALIDATE_INT) || strlen($num) > 2){ $err['num'] = ''; $flag = 1; } if (empty($num)){ $err['num'] = ''; $flag = 1; } if (!preg_match($pattern_phone, $phone)){ $err['phone'] = ''; $flag = 1; } if (empty($phone)){ $err['phone'] = ''; $flag = 1; } if (!filter_var($email, FILTER_VALIDATE_EMAIL)){ $err['email'] = ''; $flag = 1; } if (empty($email)){ $err['email'] = ''; $flag = 1; } if (!filter_var($ip, FILTER_VALIDATE_IP)){ $err['ip'] = ''; $flag = 1; } if (empty($ip)){ $err['ip'] = ''; $flag = 1; } if (!filter_var($url, FILTER_VALIDATE_URL)){ $err['url'] = ''; $flag = 1; } if (empty($url)){ $err['url'] = ''; $flag = 1; } if (empty($text)){ $err['text'] = ''; $flag = 1; } if ($flag == 0){ Header("Location:". $_SERVER['HTTP_REFERER']."?mes=success"); } } if ($_GET['mes'] == 'success'){ $err['success'] = '
Сообщение успешно отправлено!
'
; }
С 1 по 7 стр. Функция очистки данных
С 9 по 15 стр. Принимаем данные из формы прогоняя их через функцию
17 стр. Регулярное выражение для номера телефона в формате РФ
19 стр. Регулярное выражение для имени (только рус.)
20 стр. Определяем переменную, как массив ошибок
21 стр. Специальный флаг. Присвоим ему значение — 0
23 стр. Проверка, если данные пришли методом POST
С 24 по 27 стр. Проверка на соответствие регулярному выражению ($name)
С 28 по 31 стр. Если поле пустое или больше 10 символов — выводим ошибку
С 32 по 35 стр. Фильтр проверки данных на целое число и длину строки
36 стр. Проверка поля на пустоту (в коде повторяется)
С 40 по 43 стр. Проверка на соответствие регулярному выражению ($phone)
С 48 по 51 стр. Фильтр валидации Email
С 56 по 59 стр. Фильтр валидации IP
С 64 по 67 стр. Фильтр валидации URL
С 76 по 78 стр. Если валидация пройдена

Если валидация всех полей будет пройдена, об этом нам скажет специальный флаг, которому мы в начале установили ноль, то перезагрузим страницу с очисткой формы и добавим к адресу GET-параметр mes и присвоим ему значение success. То есть если 0 — валидация пройдена, если 1 — есть ошибки. И в самом конце с 80 по 82 стр. проверяем, если такой параметр существует, то выводим сообщение об успешной отправке данных. Это один из примеров валидации на PHP и он не единственный верный, но как рабочий вариант вполне пригоден для использования. Через JS и Ajax валидация будет немного по-другому реализована, но общий принцип останется таким же.

Надеюсь, что теперь у вас не возникнет трудностей с валидацией форм на PHP. Пишите ваши комментрии по данной теме.

Источник

Validate Phone Number in PHP

Validate Phone Number in PHP

  1. Use regex Regular Expression to Validate Phone Numbers in PHP
  2. Use the filter Method to Validate Phone Numbers 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.

php function validate_number($phone_number) if(preg_match('/^9+$/', $phone_number))   // the format /^7+$/ will check for phone number with 11 digits and only numbers  echo "Phone Number is Valid 
"
;
> else echo "Enter Phone Number with correct format
"
;
> > //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.

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.

php function validate_number($phone_number) if(preg_match('/^2-6$/', $phone_number))  // the format /^3-6$/ will check for phone number with 11 digits with a - after first 4 digits.  echo "Phone Number is Valid 
"
;
> else echo "Enter Phone Number with correct format
"
;
> > //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 "
"
;
function validate_country_number($phone_number) if(preg_match('/^\+8-8-5$/', $phone_number)) // the format /^\+2-1-3$/ will check for phone number with country codes, 11 or 12 digits, + and - echo "Phone Number is Valid with country code
"
;
> else echo "Enter Phone Number with correct format
"
;
> > //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"); ?>
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.

php function validate_number($phone_number) $valid_phone_number = filter_var($phone_number, FILTER_SANITIZE_NUMBER_INT); echo $valid_phone_number."
"
;
> //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.

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.

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

Источник

Оцените статью