PHPackages                             countriesdb/validator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. countriesdb/validator

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

countriesdb/validator
=====================

PHP validation client for CountriesDB with Laravel validation rules and a standalone Http-based validator for country and subdivision code checks against the CountriesDB backend API.

1.0.3(5mo ago)04proprietaryPHPPHP ^8.0

Since Dec 16Pushed 5mo agoCompare

[ Source](https://github.com/countriesdb/validator-php)[ Packagist](https://packagist.org/packages/countriesdb/validator)[ Docs](https://nayee.net)[ RSS](/packages/countriesdb-validator/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (2)Versions (5)Used By (0)

countriesdb/validator
=====================

[](#countriesdbvalidator)

**Backend validation package for CountriesDB.** Provides server-side validation for country and subdivision codes using ISO 3166-1 and ISO 3166-2 standards.

[![Latest Version](https://camo.githubusercontent.com/3a2728b0ff8a4fa26d426ff1d0b9b6f3941d1ccb8ea8dfc18d7c0e053c845d1a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f756e747269657364622f76616c696461746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/countriesdb/validator)[![Total Downloads](https://camo.githubusercontent.com/643727cbad65c979750c7df9087a4af5b6f7cde3a1cd894a87b1ef67c03aa4c0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636f756e747269657364622f76616c696461746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/countriesdb/validator)[![License](https://camo.githubusercontent.com/59719e6d47f4689861e6a3ce9c8c1468b312f3965a725689c957a8ccec7e91e2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f636f756e747269657364622f76616c696461746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/countriesdb/validator)

📖 **[Full Documentation](https://countriesdb.com/docs/backend-api)** | 🌐 **[Website](https://countriesdb.com)**

**Important**: This package only provides validation methods. Data fetching for frontend widgets must be done through frontend packages ([`@countriesdb/widget-core`](https://www.npmjs.com/package/@countriesdb/widget-core), [`@countriesdb/widget`](https://www.npmjs.com/package/@countriesdb/widget)).

Getting Started
---------------

[](#getting-started)

**⚠️ API Key Required:** This package requires a CountriesDB **private** API key to function. You must create an account at [countriesdb.com](https://countriesdb.com) to obtain your private API key. Test accounts are available with limited functionality.

- 🔑 [Get your API key](https://countriesdb.com) - Create an account and get your private key
- 📚 [View documentation](https://countriesdb.com/docs/backend-api) - Complete API reference and examples
- 💬 [Support](https://countriesdb.com) - Get help and support

Features
--------

[](#features)

- ✅ **Laravel Validation Rules** - Drop-in validation rules (`ValidCountry`, `ValidSubdivision`) for Laravel forms
- ✅ **Standalone Validator** - Use the `Validator` class directly in any PHP application
- ✅ **ISO 3166 Compliant** - Validates ISO 3166-1 (countries) and ISO 3166-2 (subdivisions) codes
- ✅ **Multiple Validation Options** - Support for `follow_upward`, `follow_related`, and `allow_parent_selection`
- ✅ **Batch Validation** - Validate multiple countries or subdivisions in a single request
- ✅ **Laravel 9-12 Support** - Compatible with Laravel 9.0, 10.0, 11.0, and 12.0
- ✅ **Detailed Error Messages** - Returns specific error messages from the CountriesDB API

Installation
------------

[](#installation)

```
composer require countriesdb/validator
```

Usage
-----

[](#usage)

### Standalone Validator

[](#standalone-validator)

```
use CountriesDB\Validator\Validator;

$validator = new Validator('YOUR_API_KEY');

// Validate a single country
$result = $validator->validateCountry('US');
if ($result['valid']) {
    echo "Valid country";
} else {
    echo "Invalid: " . $result['message'];
}

// Validate a single subdivision
$result = $validator->validateSubdivision('US-CA', 'US');
if ($result['valid']) {
    echo "Valid subdivision";
}

// Validate multiple countries
$results = $validator->validateCountries(['US', 'CA', 'MX']);
foreach ($results as $result) {
    echo $result['code'] . ': ' . ($result['valid'] ? 'Valid' : 'Invalid');
}

// Validate multiple subdivisions
$results = $validator->validateSubdivisions(
    ['US-CA', 'US-NY', 'US-TX'],
    'US'
);
```

### Laravel Validation Rules

[](#laravel-validation-rules)

#### Configuration

[](#configuration)

Add to your `config/services.php`:

```
'countriesdb' => [
    'private_key' => env('COUNTRIESDB_PRIVATE_KEY'),
    'api_url' => 'https://api.countriesdb.com',
],
```

#### Using Validation Rules

[](#using-validation-rules)

```
use CountriesDB\Validator\Rules\ValidCountry;
use CountriesDB\Validator\Rules\ValidSubdivision;

// In a FormRequest
public function rules()
{
    return [
        'country' => ['required', new ValidCountry()],
        'subdivision' => ['required', new ValidSubdivision('country')],
    ];
}

// With options
public function rules()
{
    return [
        'country' => ['required', new ValidCountry(followUpward: true)],
        'subdivision' => [
            'required',
            new ValidSubdivision(
                countryAttribute: 'country',
                followRelated: true,
                allowParentSelection: true
            ),
        ],
    ];
}
```

API Reference
-------------

[](#api-reference)

### `Validator`

[](#validator)

Main validator class.

#### Constructor

[](#constructor)

```
new Validator(string $apiKey, ?string $backendUrl = null)
```

**Parameters:**

- `apiKey` (required): Your CountriesDB API key
- `backendUrl` (optional): Backend API URL (defaults to `https://api.countriesdb.com`)

#### Methods

[](#methods)

##### `validateCountry(code, followUpward?)`

[](#validatecountrycode-followupward)

Validate a single country code.

**Parameters:**

- `code` (string): ISO 3166-1 alpha-2 country code
- `followUpward` (bool): Check if country is referenced in a subdivision (default: `false`)

**Returns:** `array` with `valid` (bool) and optional `message` (string|null)

##### `validateCountries(codes)`

[](#validatecountriescodes)

Validate multiple country codes.

**Parameters:**

- `codes` (array): Array of ISO 3166-1 alpha-2 country codes

**Returns:** `array` of results with `code`, `valid`, and optional `message`

##### `validateSubdivision(code, country, followRelated?, allowParentSelection?)`

[](#validatesubdivisioncode-country-followrelated-allowparentselection)

Validate a single subdivision code.

**Parameters:**

- `code` (string|null): Subdivision code (e.g., 'US-CA') or null/empty string
- `country` (string): ISO 3166-1 alpha-2 country code
- `followRelated` (bool): Check if subdivision redirects to another country (default: `false`)
- `allowParentSelection` (bool): Allow selecting parent subdivisions (default: `false`)

**Returns:** `array` with `valid` (bool) and optional `message` (string|null)

##### `validateSubdivisions(codes, country, allowParentSelection?)`

[](#validatesubdivisionscodes-country-allowparentselection)

Validate multiple subdivision codes.

**Parameters:**

- `codes` (array): Array of subdivision codes or null/empty strings
- `country` (string): ISO 3166-1 alpha-2 country code
- `allowParentSelection` (bool): Allow selecting parent subdivisions (default: `false`)

**Returns:** `array` of results with `code`, `valid`, and optional `message`

### Laravel Rules

[](#laravel-rules)

#### `ValidCountry`

[](#validcountry)

Laravel validation rule for country codes.

```
new ValidCountry(bool $followUpward = false)
```

#### `ValidSubdivision`

[](#validsubdivision)

Laravel validation rule for subdivision codes.

```
new ValidSubdivision(
    string $countryAttribute = 'country',
    bool $followRelated = false,
    bool $allowParentSelection = false
)
```

Examples
--------

[](#examples)

### End-to-end samples

[](#end-to-end-samples)

A full Laravel application example using this package is available in the [countriesdb/examples](https://github.com/countriesdb/examples) repository:

- [`php/backend-laravel`](https://github.com/countriesdb/examples/tree/main/php/backend-laravel) – Full Laravel application using this package's validation rules (`ValidCountry` and `ValidSubdivision`)

The example includes setup instructions and demonstrates all validation scenarios with working API routes.

### Manual Validation in Controllers

[](#manual-validation-in-controllers)

If you prefer to validate manually in your controllers instead of using Laravel validation rules:

```
use CountriesDB\Validator\Validator;

$validator = new Validator(config('services.countriesdb.private_key'));

// In your controller
$country = $request->input('country');
$subdivision = $request->input('subdivision');

$countryResult = $validator->validateCountry($country);
if (!$countryResult['valid']) {
    return response()->json(['error' => $countryResult['message']], 422);
}

$subdivisionResult = $validator->validateSubdivision($subdivision, $country);
if (!$subdivisionResult['valid']) {
    return response()->json(['error' => $subdivisionResult['message']], 422);
}

// Validation passed
```

Requirements
------------

[](#requirements)

- PHP 8.0+
- Laravel 9.0+ (or illuminate/http ^9.0|^10.0|^11.0|^12.0)
- Valid CountriesDB API key

License
-------

[](#license)

Proprietary (NAYEE LLC)

Copyright (c) NAYEE LLC. All rights reserved.

This software is the proprietary property of NAYEE LLC. For licensing inquiries, please contact [NAYEE LLC](https://nayee.net).

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance71

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~12 days

Total

4

Last Release

163d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/45282987?v=4)[nayee](/maintainers/nayee)[@Nayee](https://github.com/Nayee)

---

Top Contributors

[![nayee-dev](https://avatars.githubusercontent.com/u/244350211?v=4)](https://github.com/nayee-dev "nayee-dev (5 commits)")

---

Tags

phpcomposerlaravelvalidationcountriesISO 3166REST APIbackendapi clientgeographyiso\_3166\_2subdivisionspackagistISO 3166-1country codesserver-sideaddress validationlocation-validationcountriesdbsubdivision-codesstate-codesprovince-codescountry-validationsubdivision-validation

### Embed Badge

![Health badge](/badges/countriesdb-validator/health.svg)

```
[![Health](https://phpackages.com/badges/countriesdb-validator/health.svg)](https://phpackages.com/packages/countriesdb-validator)
```

###  Alternatives

[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77022.3M151](/packages/laravel-mcp)[wendelladriel/laravel-validated-dto

Data Transfer Objects with validation for Laravel applications

762649.9k18](/packages/wendelladriel-laravel-validated-dto)[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.4M50](/packages/proengsoft-laravel-jsvalidation)[intervention/validation

Additional validation rules for the Laravel framework

6827.2M20](/packages/intervention-validation)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M131](/packages/roots-acorn)[galahad/laravel-addressing

Laravel package providing addressing functionality

71335.3k](/packages/galahad-laravel-addressing)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
