axlon/laravel-postal-code-validation
Installation:
composer require axlon/laravel-postal-code-validation
For Lumen, ensure the service provider is registered in bootstrap/app.php:
$app->register(\Axlon\PostalCodeValidation\PostalCodeValidationServiceProvider::class);
First Use Case: Validate a postal code in a Laravel Form Request:
use Axlon\PostalCodeValidation\Rules\PostalCode;
public function rules()
{
return [
'postal_code' => ['required', new PostalCode],
];
}
Where to Look First:
Form Validation:
Use the PostalCode rule in Laravel's built-in validation:
$request->validate([
'postal_code' => ['required', new PostalCode('US')], // Validate for US only
]);
Fluent API for Dynamic Validation: Chain methods for flexible validation:
$validator = Validator::make($data, [
'postal_code' => new PostalCode,
]);
$validator->after(function ($validator) {
$validator->addRules([
'postal_code' => new PostalCode('GB', 'EH1 1AA'), // Validate against a specific format
]);
});
Manual Validation: Validate outside of form requests:
use Axlon\PostalCodeValidation\Facades\PostalCodeValidator;
$isValid = PostalCodeValidator::validate('SW1A 1AA', 'GB');
Custom Error Messages: Override default messages in your request or controller:
$messages = [
'postal_code.postal_code' => 'The :attribute format is invalid for the selected country.',
];
$request->validate([...], $messages);
Country-Specific Validation: Pass a country code (ISO 3166-1 alpha-2) to restrict validation to a specific country:
new PostalCode('CA') // Validates Canadian postal codes (A1A 1A1)
Regex Overrides: Extend the package to support custom regex patterns for unsupported countries:
PostalCode::extend('MY', '^\d{5}$'); // Custom regex for Malaysia
Laravel Nova: Use the rule in Nova validation:
use Axlon\PostalCodeValidation\Rules\PostalCode;
public static $rules = [
'postal_code' => ['required', new PostalCode('DE')],
];
API Responses: Return validation errors in API responses:
return response()->json([
'errors' => $validator->errors(),
], 422);
Country Code Sensitivity:
US, GB, CA).USA or United States will fail. Use US instead.No Default Country:
new PostalCode('GB') // Explicitly validate for UK
Rate Limiting:
PostalCodeValidator::validate() method sparingly in bulk operations.Edge Cases:
US, CA) have variable-length formats (e.g., 90210 or A1B 2C3).123) may pass validation unintentionally.regex rule for stricter validation:
new PostalCode('US'), 'regex:/^\d{5}(-\d{4})?$/'
Enable Debug Mode: Temporarily enable debug logging to inspect validation logic:
\Axlon\PostalCodeValidation\PostalCodeValidator::setDebug(true);
Check Supported Countries: Run this to list all supported countries:
dd(\Axlon\PostalCodeValidation\PostalCodeValidator::supportedCountries());
Custom Regex Testing: Test custom regex patterns before extending the package:
preg_match('/^\d{5}$/', '12345'); // Test manually
Add New Countries: Extend the validator with custom rules:
PostalCode::extend('AU', '^\d{4}$'); // Australian postcodes
Override Validation Logic: Publish the config and customize:
php artisan vendor:publish --provider="Axlon\PostalCodeValidation\PostalCodeValidationServiceProvider"
Modify config/postal-code-validation.php to adjust default rules or messages.
Mock for Testing: Use Laravel’s mocking to avoid external API calls in tests:
PostalCodeValidator::shouldReceive('validate')
->once()
->with('SW1A 1AA', 'GB')
->andReturn(true);
Fallback for Unsupported Countries: Implement a fallback rule for unsupported countries:
$validator->after(function ($validator) {
if ($validator->failed() && $validator->errors()->has('postal_code')) {
$validator->errors()->add('postal_code', 'Unsupported country for postal code validation.');
}
});
Cache Validation Results: Cache results for frequently validated postal codes:
$cacheKey = "postal_code:{$postalCode}:{$country}";
$isValid = Cache::remember($cacheKey, now()->addHours(1), function () use ($postalCode, $country) {
return PostalCodeValidator::validate($postalCode, $country);
});
Batch Validation: For bulk validation (e.g., CSV imports), use a queue job to avoid rate limits:
PostalCodeValidator::validateBatch($postalCodes, $country);
How can I help you explore Laravel packages today?