Phone Number Formatting, Validation, and Model Casts in Laravel | ggn_sh

Phone Number Formatting, Validation, and Model Casts in Laravel | ggn_sh

The Laravel-Phone package makes working with phone numbers in PHP and Laravel a breeze, offering validation rules, attribute casting, utility helpers, and more.

Demo

Check out the behavior of this package in the demo.

Installation

Run the following command to install the latest applicable version of the package:

composer require propaganistas/laravel-phone        

The Service Provider gets discovered automatically by Laravel.

In your languages directory, add an extra translation in every validation.php language file:

'phone' => 'The :attribute field must be a valid number.',        

Validation

Use the phone keyword in your validation rules array or use the Propaganistas\LaravelPhone\Rules\Phone rule class to define the rule in an expressive way.

To put constraints on the allowed originating countries, you can explicitly specify the allowed country codes.

'phonefield'       => 'phone:US,BE',
// 'phonefield'    => (new Phone)->country(['US', 'BE'])        

Or to make things more dynamic, you can also match against another data field holding a country code. For example, to require a phone number to match the provided country of residence. 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:

'phonefield'            => 'phone',
// 'phonefield'         => (new Phone)
'phonefield_country'    => 'required_with:phonefield',        
'phonefield'            => 'phone:custom_country_field',
// 'phonefield'         => (new Phone)->countryField('custom_country_field')
'custom_country_field'  => 'required_with:phonefield',        

Note: country codes should be ISO 3166-1 alpha-2 compliant.

To support any valid internationally formatted phone number next to the whitelisted countries, use the INTERNATIONAL parameter. This can be useful when you're expecting locally formatted numbers from a specific country but also want to accept any other foreign number entered properly:

'phonefield'            => 'phone:INTERNATIONAL,BE',
// 'phonefield'         => (new Phone)->international()->country('BE')        

To specify constraints on the number type, just append the allowed types to the end of the parameters, e.g.:

'phonefield'       => 'phone:mobile',
// 'phonefield'    => (new Phone)->type('mobile')        

The most common types are mobile and fixed_line, but feel free to use any of the types defined here.

Prepend a type with an exclamation mark to blacklist it instead. Note that you can never use whitelisted and blacklisted types at the same time.

'phonefield'       => 'phone:!mobile',
// 'phonefield'    => (new Phone)->notType('mobile')        

You can also enable lenient validation by using the LENIENT parameter. With leniency enabled, only the length of the number is checked instead of actual carrier patterns.

'phonefield'       => 'phone:LENIENT',
// 'phonefield'    => (new Phone)->lenient()        

Have you ever built validation around phone numbers that supports multiple countries? This package has helpful validation rules built in, which makes it easy to validate numbers for any country. You can specify acceptible country code formats, but at the same time accept valid "international" numbers:

// Validate either USA or Belguim
Validator::make($request->all(), [
    'phone_number' => 'phone:US,BE',
]);
 
// Validate US specifically, but also accept other countries
Validator::make($request->all(), [
    'phone_number' => 'phone:US,INTERNATIONAL',
]);
 
// Use the Phone rule
Validator::make($request->all(), [
    'phone_number' => (new Phone)->country(['US', 'BE']),
]);
 
// Match country code against another data field
Validator::make($request->all(), [
    'phone_number' => (new Phone)->countryField('custom_country_field'),
    'custom_country_field' => 'required_with:phone_number',
]);        

This package uses the PHP port of Google's phone number handling library under the hood, which has robust parsing, formatting, and validation capabilities for working with phone numbers in PHP:

// Formatting examples
 
$phone = new PhoneNumber('012/34.56.78', 'BE');
 
$phone->format($format);       // Custom formatting
$phone->formatE164();          // +3212345678
$phone->formatInternational(); // +32 12 34 56 78
$phone->formatRFC3966();       // +32-12-34-56-78
$phone->formatNational();      // 012 34 56 78        

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

要查看或添加评论,请登录

Gagan Kumar Sharma的更多文章

社区洞察

其他会员也浏览了