npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@countriesdb/validator

v0.1.4

Published

Backend validation package for CountriesDB - server-side validation for country and subdivision codes

Readme

@countriesdb/validator

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

📖 Full Documentation | 🌐 Website

Important: This package only provides validation methods. Data fetching for frontend widgets must be done through frontend packages (@countriesdb/widget-core, @countriesdb/widget).

Getting Started

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

Installation

npm install @countriesdb/validator

Usage

Basic Validation

import { CountriesDBValidator } from '@countriesdb/validator';

const validator = new CountriesDBValidator({
  apiKey: 'YOUR_API_KEY',
});

// Validate a single country
const result = await validator.validateCountry('US');
console.log(result); // { valid: true } or { valid: false, message: '...' }

// Validate a single subdivision
const subdivisionResult = await validator.validateSubdivision('US-CA', 'US');
console.log(subdivisionResult); // { valid: true } or { valid: false, message: '...' }

Multiple Values

// Validate multiple countries
const results = await validator.validateCountries(['US', 'CA', 'MX']);
// Returns: [{ code: 'US', valid: true }, { code: 'CA', valid: true }, ...]

// Validate multiple subdivisions
const subdivisionResults = await validator.validateSubdivisions(
  ['US-CA', 'US-NY', 'US-TX'],
  'US'
);
// Returns: [{ code: 'US-CA', valid: true }, ...]

Validation Options

// Country validation with follow_upward
const result = await validator.validateCountry('US', {
  followUpward: true, // Check if country is referenced in a subdivision
});

// Subdivision validation with options
const result = await validator.validateSubdivision('US-CA', 'US', {
  followRelated: true, // Check if subdivision redirects to another country
  allowParentSelection: true, // Allow selecting parent subdivisions
});

API Reference

CountriesDBValidator

Main validator class.

Constructor

new CountriesDBValidator(config: CountriesDBBackendConfig)

Config:

  • apiKey (required): Your CountriesDB API key

Methods

validateCountry(code, options?)

Validate a single country code.

Parameters:

  • code (string): ISO 3166-1 alpha-2 country code
  • options (optional):
    • followUpward (boolean): Check if country is referenced in a subdivision

Returns: Promise<ValidationResult>

validateCountries(codes, options?)

Validate multiple country codes.

Parameters:

  • codes (string[]): Array of ISO 3166-1 alpha-2 country codes
  • options (optional):
    • followUpward (boolean): Always false for multi-value (disabled)

Returns: Promise<ValidationResult[]>

validateSubdivision(code, country, options?)

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
  • options (optional):
    • followRelated (boolean): Check if subdivision redirects to another country
    • allowParentSelection (boolean): Allow selecting parent subdivisions

Returns: Promise<ValidationResult>

validateSubdivisions(codes, country, options?)

Validate multiple subdivision codes.

Parameters:

  • codes ((string | null)[]): Array of subdivision codes or null/empty strings
  • country (string): ISO 3166-1 alpha-2 country code
  • options (optional):
    • allowParentSelection (boolean): Allow selecting parent subdivisions

Returns: Promise<ValidationResult[]>

Types

interface ValidationResult {
  valid: boolean;
  message?: string | null;
  code?: string; // Present in multi-value results
}

interface ValidationOptions {
  followUpward?: boolean;
}

interface SubdivisionValidationOptions {
  followRelated?: boolean;
  allowParentSelection?: boolean;
}

Examples

Express.js Validation Middleware

import { CountriesDBValidator } from '@countriesdb/validator';
import express from 'express';

const validator = new CountriesDBValidator({
  apiKey: process.env.COUNTRIESDB_API_KEY!,
});

const app = express();

app.post('/api/user', async (req, res) => {
  const { country, subdivision } = req.body;

  // Validate country
  const countryResult = await validator.validateCountry(country);
  if (!countryResult.valid) {
    return res.status(422).json({ error: countryResult.message });
  }

  // Validate subdivision
  const subdivisionResult = await validator.validateSubdivision(
    subdivision,
    country
  );
  if (!subdivisionResult.valid) {
    return res.status(422).json({ error: subdivisionResult.message });
  }

  // Proceed with user creation
  // ...
});

Next.js API Route

import { CountriesDBValidator } from '@countriesdb/validator';
import type { NextApiRequest, NextApiResponse } from 'next';

const validator = new CountriesDBValidator({
  apiKey: process.env.COUNTRIESDB_API_KEY!,
});

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { codes, country } = req.body;

  if (Array.isArray(codes)) {
    // Multi-value validation
    const results = await validator.validateCountries(codes);
    return res.status(200).json({ results });
  } else {
    // Single value validation
    const result = await validator.validateCountry(codes);
    return res.status(result.valid ? 200 : 422).json(result);
  }
}

Error Handling

All methods handle network errors and API errors gracefully:

try {
  const result = await validator.validateCountry('US');
  if (!result.valid) {
    console.error('Validation failed:', result.message);
  }
} catch (error) {
  console.error('Network error:', error);
}

Full backend examples

Clone-and-run projects that use this package (and the other SDKs) are available in the CountriesDB examples repository:

  • javascript/backend-fetch – native fetch
  • javascript/backend-axios – axios wrapper
  • php/backend-laravel – PHP/Laravel validation rules
  • php/backend-guzzle – vanilla PHP + Guzzle
  • python/backend-requests – Python requests library
  • java/backend-httpclient and backend-spring – Java examples
  • csharp/backend-httpclient – C# .NET examples
  • go/backend-http – Go examples
  • ruby/backend-faraday – Ruby examples
  • bash/backend-curl – Bash cURL examples

Each folder includes a README with setup instructions so you can test the flows end-to-end.

Requirements

  • Node.js 18+ (uses native fetch API)
  • Valid CountriesDB private API key (Get your API key)

Additional Resources

License

PROPRIETARY

Copyright (c) NAYEE LLC. All rights reserved.

This software is the proprietary property of NAYEE LLC. For licensing inquiries, please contact NAYEE LLC.