PHP code example of countriesdb / validator

1. Go to this page and download the library: Download countriesdb/validator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

countriesdb / validator example snippets


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

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

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

// In a FormRequest
public function rules()
{
    return [
        'country' => ['idCountry(followUpward: true)],
        'subdivision' => [
            '

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

new ValidCountry(bool $followUpward = false)

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

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