Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Postal Code Validation Laravel Package

axlon/laravel-postal-code-validation

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. 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);
    
  2. 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],
        ];
    }
    
  3. Where to Look First:


Implementation Patterns

Core Workflows

  1. Form Validation: Use the PostalCode rule in Laravel's built-in validation:

    $request->validate([
        'postal_code' => ['required', new PostalCode('US')], // Validate for US only
    ]);
    
  2. 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
        ]);
    });
    
  3. Manual Validation: Validate outside of form requests:

    use Axlon\PostalCodeValidation\Facades\PostalCodeValidator;
    
    $isValid = PostalCodeValidator::validate('SW1A 1AA', 'GB');
    
  4. 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);
    

Integration Tips

  • 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);
    

Gotchas and Tips

Pitfalls

  1. Country Code Sensitivity:

    • The package uses ISO 3166-1 alpha-2 country codes (e.g., US, GB, CA).
    • Gotcha: Passing USA or United States will fail. Use US instead.
    • Fix: Normalize country codes in your application logic if needed.
  2. No Default Country:

    • If no country is specified, the rule validates any postal code format.
    • Gotcha: This may lead to false positives for invalid formats in unsupported countries.
    • Fix: Always specify a country code when possible:
      new PostalCode('GB') // Explicitly validate for UK
      
  3. Rate Limiting:

    • The package relies on Google’s Address Data Service for validation.
    • Gotcha: Excessive requests may trigger rate limits or incur costs.
    • Fix:
      • Cache validation results (e.g., using Laravel’s cache).
      • Use the PostalCodeValidator::validate() method sparingly in bulk operations.
  4. Edge Cases:

    • Some countries (e.g., US, CA) have variable-length formats (e.g., 90210 or A1B 2C3).
    • Gotcha: Partial or malformed inputs (e.g., 123) may pass validation unintentionally.
    • Fix: Combine with Laravel’s regex rule for stricter validation:
      new PostalCode('US'), 'regex:/^\d{5}(-\d{4})?$/'
      

Debugging

  1. Enable Debug Mode: Temporarily enable debug logging to inspect validation logic:

    \Axlon\PostalCodeValidation\PostalCodeValidator::setDebug(true);
    
  2. Check Supported Countries: Run this to list all supported countries:

    dd(\Axlon\PostalCodeValidation\PostalCodeValidator::supportedCountries());
    
  3. Custom Regex Testing: Test custom regex patterns before extending the package:

    preg_match('/^\d{5}$/', '12345'); // Test manually
    

Extension Points

  1. Add New Countries: Extend the validator with custom rules:

    PostalCode::extend('AU', '^\d{4}$'); // Australian postcodes
    
  2. 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.

  3. Mock for Testing: Use Laravel’s mocking to avoid external API calls in tests:

    PostalCodeValidator::shouldReceive('validate')
        ->once()
        ->with('SW1A 1AA', 'GB')
        ->andReturn(true);
    
  4. 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.');
        }
    });
    

Performance Tips

  • 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);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope