Worldwide postal code validation for Laravel
Worldwide postal code validation for Laravel, based on Google's Address Data Service.
This package has the following requirements:
- PHP 7.1 or higher
- Laravel (or Lumen) 5.1 or higher
You can install this package with Composer, by running the command below:
composer require axlon/laravel-postal-code-validation
If you use Laravel 5.5 or higher, that's it, continue to the usage section.
If you're using an older version of Laravel, register the package's service provider to your application. You can do
this by adding the following line to your
'providers' => [ ... Axlon\PostalCodeValidation\ValidationServiceProvider::class, ... ],
If you are using Lumen, register the package by adding the following line to your
Postal code validation perfectly integrates into your Laravel application, you can use it just like you would any framework validation rule.
This package adds the following validation rules:
The field under validation must be a valid postal code in at least one of the given countries. Arguments must be countries in ISO 3166-1 alpha-2 format.
'postal_code' => 'postal_code:NL,DE,FR,BE'
The field under validation must be a postal code in at least one of the countries in the given fields only if at least one of the specified fields is present.
'billing.country' => 'required|string|max:2', ... 'shipping.country' => 'nullable|string|max:2', 'shipping.postal_code' => 'postal_code_for:billing.country,shipping.country'
Important: while this rule supports array references (e.g.
postal_code_for:deliveries.*.country), this will not
work in Laravel 5.1-5.3 due to framework limitations.
If you prefer using a fluent object style over string based rules, that's also available:
'postal_code' => [ PostalCode::forCountry('NL')->or('BE'), ],
The same goes for the
'billing.country' => 'required|string|max:2', ... 'shipping.country' => 'nullable|string|max:2', 'shipping.postal_code' => [ PostalCode::forInput('billing.country')->or('shipping.country') ],
To add a meaningful error message, add the following lines to
'postal_code' => 'Your message here', 'postal_code_for' => 'Your message here',
The following placeholders will be automatically filled for you:
|:attribute||The name of the field that was under validation|
|:countries||The countries that were validated against (e.g.
|:examples||Examples of allowed postal codes (e.g.
:examples placeholders may be empty if no valid countries are passed.
If you want to validate postal codes manually outside of Laravel's validation system, you can call the validator directly, like so:
$validator = app('\Axlon\PostalCodeValidation\Validator'); $validator->validate($countryCode, $postalCode); // returns a boolean
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.