валидация номера телефона laravel
Как проверить номер телефона в laravel 5.2?
Я хочу подтвердить ввод телефонного номера пользователя, где номер должен быть ровно 11 и начинается с 01, а поле значения должно быть только числом. Как мне сделать это с помощью проверки Laravel?
Вот мой контроллер:
Решение
Одним из возможных решений было бы использовать регулярное выражение.
Это проверит, что ввод начинается с 01 и сопровождается 9 числами. С помощью регулярных выражений вам не нужно numeric или же size правила проверки.
Если вы хотите использовать этот метод проверки в другом месте, было бы неплохо создать собственное правило проверки для проверки телефонных номеров.
В вашем AppServiceProvider «s boot метод:
Это позволит вам использовать phone_number Правило проверки в любом месте вашего приложения, поэтому проверка вашей формы может быть:
Другие решения
Вставьте этот код в app/Providers/AppServiceProvider.php загрузиться с вашим приложением.
Это правило проверяет номер телефона по приведенному выше шаблону, который я нашел после
длительный поиск соответствует самым распространенным номерам мобильных или телефонных номеров во многих странах
Это позволит вам использовать phone Правило проверки в любом месте вашего приложения, поэтому проверка вашей формы может быть:
использование
required|numeric|size:11
Вместо
required|min:11|numeric
Начиная с Laravel 5.5 вы можете использовать команду ремесленника для создания нового правила, которое вы можете кодировать в соответствии с вашими требованиями, чтобы решить, будет оно выполнено или нет.
Ej:
php artisan make:rule PhoneNumber
Затем используйте это правило, как вы обычно делаете с проверкой:
Вы можете попробовать этот пакет проверки телефона. Laravel Phone
Обновить
Есть много вещей, которые следует учитывать при проверке номера телефона, если вы действительно думаете об этом. (особенно в международном масштабе), поэтому использование пакета намного лучше, чем принятый ответ, и если вы хотите что-то простое, например, регулярное выражение, я бы предложил использовать что-то лучшее, чем то, что предлагал @SlateEntropy. (что-то вроде Комплексное регулярное выражение для проверки номера телефона )
Валидация номера телефона laravel
Adds phone number functionality to Laravel based on the PHP port of Google’s libphonenumber API by giggsey.
Check out the behavior of this package in the demo.
Run the following command to install the latest applicable version of the package:
The Service Provider gets discovered automatically by Laravel.
In your languages directory, add an extra translation in every validation.php language file:
To validate a phone number, use the phone keyword in your validation rules array or use the Phone rule class to define the rule in an expressive way. The phone validator is able to operate in three ways.
You either specify ISO 3166-1 alpha-2 compliant country codes yourself as parameters for the validator, e.g.:
The validator will check if the number is valid in at least one of provided countries, so feel free to add as many country codes as you like.
You provide a dedicated country input field (keyed by ISO 3166-1 compliant country codes) to allow end users to supply a country on their own. Make sure the country field has the same name as the phone field but with _country appended for automatic discovery, or provide your custom country field name as a parameter to the validator:
You instruct the validator to detect which country the number belongs to using the AUTO keyword (and optionally any fallback countries):
To specify constraints on the number type, just append the allowed types to the end of the parameters, e.g.:
You can also enable more lenient validation (for example, fixed lines without area codes) by using the LENIENT parameter. This feature inherently doesn’t play well with country autodetection and number type validation, so use such combo at own risk.
Two cast classes are provided for automatic casting of Eloquent model attributes:
Both classes automatically cast the database value to a PhoneNumber object for further use in your application.
When setting a value, they both accept a string value or a PhoneNumber object. The RawPhoneNumberCast mutates the database value to the raw input number, while the E164PhoneNumberCast writes a formatted E.164 phone number to the database.
Both classes accept cast parameters in the same way:
In order to not encounter any unexpected issues when using these casts, please always validate any input using the validation rules previously described.
⚠️ Attribute assignment and E164PhoneNumberCast
Due to the nature of E164PhoneNumberCast a valid country attribute is expected if the number is not passed in international format. Since casts are applied in the order of the given values, be sure to set the country attribute before setting the phone number attribute. Otherwise E164PhoneNumberCast will encounter an empty country value and throw an unexpected exception.
Utility PhoneNumber class
A phone number can be wrapped in the Propaganistas\LaravelPhone\PhoneNumber class to enhance it with useful utility methods. It’s safe to directly reference these objects in views or when saving to the database as they will degrade gracefully to the E.164 format.
A PhoneNumber can be formatted in various ways:
Get some information about the phone number:
Disclaimer: Phone number handling is quite different in each application. The topics mentioned below are therefore meant as a set of thought starters; support will not be provided.
Storing phone numbers in a database has always been a speculative topic and there’s simply no silver bullet. It all depends on your application’s requirements. Here are some things to take into account, along with an implementation suggestion. Your ideal database setup will probably be a combination of some of the pointers detailed below.
The E.164 format globally and uniquely identifies a phone number across the world. It also inherently implies a specific country and can be supplied as-is to the phone() helper.
Presenting the phone number the way it was inputted
If you store formatted phone numbers the raw user input will unretrievably get lost. It may be beneficial to present your users with their very own inputted phone number, for example in terms of improved user experience.
Searching through phone numbers can quickly become ridiculously complex and will always require deep understanding of the context and extent of your application. Here’s a possible approach covering quite a lot of «natural» use cases.
Build a Phone Number Validator with Laravel
Data validation is essential to any application, regardless of its size and purpose. Without it, you risk using data that’s forged by malicious actors, contains only junk—or is a combination of both. And it doesn’t matter where the data comes from either; whether from a web form, retrieved from a database, or read from an environment setting.
Gladly, validation is extremely common in modern software development, so much so that there are numerous third-party packages available on Packagist, and PHP’s major frameworks all have a validation component. With them, you can validate email addresses, passwords, dates, IP addresses, numbers and so much more!
However, what happens when the package or framework doesn’t support your use case, such as validating a phone number? In that case, you roll your own!
In this tutorial, we’re going to build a custom Laravel validation rule object that validates a phone number from any country in the world, and then show you several ways of using it.
We’re not verifying if a phone number is in the possession of a given person, active, and so on. We’re just validating if a given string forms a valid phone number.
Prerequisites
To complete the tutorial, you will need the following things:
Create the base Laravel application
The first thing to do is to bootstrap a Laravel application. There are several ways to do that, such as the Laravel installer and Laravel Sail. However, one of the simplest is with Composer, by running the commands below.
The commands will create the application in a new directory named twilio-phone-number-validator. To save a bit of time, the commands also change to the new directory and use the Artisan console to launch the application listening on localhost on port 8000.
If you open http://localhost:8000 in your browser of choice, it should look similar to the screenshot below.
Retrieve and register environment variables
With the base application ready to go, you next need to retrieve your Twilio credentials and store them in Laravel’s configuration. We need the credentials as the Lookup API requires authentication.
First, add the code below to the end of your .env file, located in the application’s root directory.
Then, from the Twilio Console’s Dashboard, which you can see below, copy your «Account SID» and «Auth Token» and replace the respective placeholders in .env with them.
Add the required dependencies
Before we can write some custom code, we need to install the required dependencies. Gladly, there’s only one: Twilio’s PHP Helper Library. To install it, run the command below.
Create a lookup service
Now, let’s write some code!
We’ll start by creating a small service class to encapsulate the logic for interacting with Twilio’s Lookup API. Yes, we could write the code directly in a controller, but doing so isn’t the most inspiring. It’s not the most flexible either.
By using a lookup service, we can validate the number in a variety of different ways and contexts, should the need arise. To do that, from the command line, create a new nested directory structure, app/Service/Twilio, by running the commands below.
If you’re using Microsoft Windows, use the following commands instead.
Next, create a new file, app/Service/Twilio/PhoneNumberLookupService.php, in your editor or IDE and paste the following code into it. Then, let’s step through what it’s doing together.
PhoneNumberLookupService has one purpose: to validate a phone number, which it does in the validate method.
As the request returns information in the response, it might seem wasteful to throw that information away. However, using the Lookup API can be far less work than creating a regular expression capable of validating every possible phone number yourself. Plus, the Lookup API doesn’t provide a pure validation endpoint.
Create a custom validation rule
With the lookup service finished, we’re now going to create a custom validation rule that will use it to validate a phone number.
First, in the terminal, run the command below to have Artisan create the core of the class in app/Rules/PhoneNumberLookup.php.
Then, replace the body of the class with the code below (formatted for readability).
The passes method determines if the rule passes or not; an apt method name, no? It takes two arguments:
The message method provides a suitable validation error message which is displayed to the user, should the phone number fail validation. It’s quite a generic message, but it’s suitable for this tutorial.
NOTE: Check out how to customize and localize error messages, if you want to display the message in multiple languages.
Before we move on, don’t forget to add the required use statement below, if your text editor or IDE doesn’t auto-complete them for you.
Create a new controller
Now that the plumbing code, if you will, has been written, we’ll create a new controller class, named PhoneNumberController, that will use the new Rule to validate a request which contains a phone number.
Use Artisan to generate the core of the controller in app/Http/Controllers by running the command below.
Then, use the code below as the body of the new class.
Laravel validation rule — telephone
In this new series, we’ll be exploring the concept of custom validation rules in Laravel and why you’ll want to use them. I’m aiming to release a new article each day containing a new rule which you can use in your own projects. I’ll also be collecting these rules into a package that you can pull in via composer.
Recap
If you’re unfamiliar with the reasoning behind creating custom rules to handle data validation, check out the intro section from the first article in this series.
You may also want to review the section on creating a rule (in the same post), as we won’t be repeating the mechanics of each method in your validation classes, we’ll just be exploring the code required to make the rule work.
Promotion
I’ve recently released Pulse — a friendly, affordable server and site monitoring service designed specifically for developers. It includes all the usual hardware monitors, custom service monitors, alerting via various notification channels, logs, as well as full API support. Take a look… https://pulse.alphametric.co
The check and response
Let’s begin by writing the logic necessary to ensure that the user has provided a valid phone number. Per current conventions, a phone number is valid if it is between 7 and 15 characters long and only includes integers.
As with the strong password rule we created, the easiest way to enforce each of these requirements, is to use a regular expression:
Next, we’ll need to write an error message to return when the user has not supplied a valid phone number:
Testing it works
As before, we’ll write a quick unit test to confirm that the regular expression works correctly and rejects invalid phone numbers:
Wrapping Up
We now have a reusable validation rule to ensure that users supply a valid telephone number when we require it. We also respond with a suitable error message when the check fails, and we have a test to ensure the rule works.
You can see the complete class and pull it into your projects by visiting the repo on Github: https://github.com/alphametric/laravel-validation-rules
I have additional validation rules that I intend to share with you in the coming days, so be sure to follow me for those articles. If you’re interested, you can also follow me on Twitter to see everything I’m up to.
40 дополнительных правил валидации в Laravel
В системе валидации Laravel существует более 60 правил, но, вдруг, вам нужно что-то особенное? Вы можете легко создать свои собственные правила проверки или же использовать те, что есть в Интернете. Давайте посмотрим, что же там есть.
22 правила от Alphametric
Начнем с Мэтта Кингшотта, старшего разработчика компании Alphametric.
Он написал довольно много статей на Medium и добавил все правила в репозиторий Github. Вот их список:
8 правил от Скотта Робинсона
Еще один хороший набор правил сделан Скоттом Робинсоном. Они находятся на сайте laravel-validation-rules.github.io:
5 правил от Spatie
Наша любимая команда Spatie также имеет свой собственный репозиторий с несколькими правилами:
5 правил от Pineco.de
В конце 2017 года, Gergő D. Nagy из Pineco.de опубликовал статью с набором правил проверки и репозиторий. С тех пор он не обновлялся, поэтому используйте с осторожностью. Правила таковы:
Проверка пароля пользователя
Четные и Нечетные числа
Значение может быть только увеличено
Значение содержит конкретные слова
День должен быть рабочим днем
Наш Телеграм-канал — следите за новостями о Laravel.
Задать вопросы по урокам можно на нашем форуме.