jekk0/laravel-iso3166-validation-rules

Laravel/Lumen validation rules for validate country codes (ISO3166-1)

1.6.1 2024-11-01 13:16 UTC

README

Build Status Coverage Status Latest Stable Version Total Downloads

Requirements

  • Laravel/Lumen 5.8.x (version 1.0.1)
  • Laravel/Lumen 6.0.x (version 1.1.0)
  • Laravel/Lumen 7.0.x (version 1.2.0)
  • Laravel/Lumen 8.0.x (version 1.3.0)
  • Laravel/Lumen 9.0.x (version 1.4.0)
  • Laravel/Lumen 10.0.x (version 1.5.0)
  • Laravel/Lumen 11.0.x (version 1.6.1)

Installation

Install the latest version with

 $ composer require jekk0/laravel-iso3166-validation-rules

Quick start.

Using in controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Jekk0\Laravel\Iso3166\Validation\Rules\Iso3166Alpha2;

class Test extends Controller
{
    public function index(Request $request)
    {
        // Request example: http://127.0.0.1:8000/t?country=us

        $rules = ['country' => ['required', new Iso3166Alpha2()]]; // ISO3166-1 Alpha2 validation rule

        try {
            $request->validate($rules);
        } catch (\Exception $exception) {
            dd('Country code is invalid: ' . $exception->getMessage());
        }

        dd('Country code is valid: ' . $request->get('country'));
    }
}

Available rules

<?php
use Jekk0\Laravel\Iso3166\Validation\Rules\Iso3166Alpha2;
use Jekk0\Laravel\Iso3166\Validation\Rules\Iso3166Alpha3;
use Jekk0\Laravel\Iso3166\Validation\Rules\Iso3166Numeric;

$rules = ['countryAlpha2' => ['required', new Iso3166Alpha2()]]; // ISO3166-1 Alpha2 validation rule
$rules = ['countryAlpha3' => ['required', new Iso3166Alpha3()]]; // ISO3166-1 Alpha3 validation rule
$rules = ['countryNumeric' => ['required', new Iso3166Numeric()]]; // ISO3166-1 Numeric validation rule

Customise error message

<?php
...
    public function index(Request $request)
    {
        // Request example: http://127.0.0.1:8000/t?country=INVALID_INPUT

        $iso3166Alpha2Rule = (new Iso3166Alpha2())->setErrorMessage('New Custom Error Message :attribute = :input');

        $rules = ['country' => ['required', $iso3166Alpha2Rule]]; // ISO3166-1 Alpha2 validation rule

        try {
            $request->validate($rules);
        } catch (\Exception $exception) {
            dd('Country code is invalid: ' . $exception->getMessage());
        }

        dd('Country code is valid: ' . $request->get('country'));
    }
    
    // Output
    // Country code is invalid: New Custom Error Message country = INVALID_INPUT

Laravel/Lumen automatically parse error message and replace:

  • :attribute -> form parameter name
  • :input -> form parameter value

Docs