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

universal-id-validator

v1.0.5

Published

A validator for different types of personal ID for multiple countries.

Readme

universal-id-validator

This package is a fork of id-doc-validator, removing the optional chain to provide greater compatibility.

A validator for different types of personal, entity and VAT IDs for multiple countries.

🚀 Quick Start Guide

Installation

Install the package using npm or yarn:

npm install universal-id-validator
# OR
yarn add universal-id-validator

Basic Usage

const {
  isValidIdDoc,
  isValidVat,
  isValidViesVat,
  supportedCountriesIdDoc,
  supportedCountriesVat,
  supportedIdDocsByCountry
} = require('universal-id-validator');

📖 Usage Examples

Validating Personal ID Documents

Example 1: Validate a Spanish NIF

const { isValidIdDoc } = require('universal-id-validator');

// Validate a Spanish NIF (Número de Identificación Fiscal)
const isValid = isValidIdDoc('12345678Z', 'ES', 'nif');
console.log(isValid); // true or false

Example 2: Validate a German Passport

const { isValidIdDoc } = require('universal-id-validator');

// Validate a German passport
const isValid = isValidIdDoc('C01X00T47', 'DE', 'passport');
console.log(isValid); // true or false

Example 3: Auto-detect document type

const { isValidIdDoc } = require('universal-id-validator');

// Let the validator check all supported document types for Portugal
const isValid = isValidIdDoc('12345678', 'PT');
// Will try: CC, NIF, and Passport formats
console.log(isValid); // true if valid for any supported type

Validating VAT Numbers

Example 4: Validate a VAT number (includes country code)

const { isValidVat } = require('universal-id-validator');

// Validate a Spanish VAT number
const isValid = isValidVat('ESB12345678');
console.log(isValid); // true or false

// Validate a German VAT number
const isValidDE = isValidVat('DE123456789');
console.log(isValidDE); // true or false

Example 5: Validate VAT using VIES API (EU only)

const { isValidViesVat } = require('universal-id-validator');

// Validate using the European Commission's VIES system
async function checkVat() {
  const result = await isValidViesVat('12345678', 'ES');
  console.log(result);
  // Returns:
  // {
  //   isValid: true/false,
  //   userError: 'VALID' | 'INVALID' | error code,
  //   vatNumber: '12345678'
  // }
}

checkVat();

Getting Supported Countries and Document Types

Example 6: List all supported countries for ID documents

const { supportedCountriesIdDoc } = require('universal-id-validator');

const countries = supportedCountriesIdDoc();
console.log(countries); // ['AT', 'BE', 'BG', 'BR', 'CA', 'CY', ...]

Example 7: List all supported document types for a specific country

const { supportedIdDocsByCountry } = require('universal-id-validator');

const ptDocTypes = supportedIdDocsByCountry('PT');
console.log(ptDocTypes); // ['cc', 'nif', 'passport']

const esDocTypes = supportedIdDocsByCountry('ES');
console.log(esDocTypes); // ['nif', 'nie', 'passport']

Example 8: List all countries that support VAT validation

const { supportedCountriesVat } = require('universal-id-validator');

const vatCountries = supportedCountriesVat();
console.log(vatCountries); // ['AT', 'BE', 'BG', 'BR', 'CO', 'CY', ...]

💡 Common Use Cases

Form Validation

const { isValidIdDoc } = require('universal-id-validator');

function validateUserIdDocument(idNumber, country, docType) {
  if (!idNumber || !country) {
    return { valid: false, message: 'ID number and country are required' };
  }

  const isValid = isValidIdDoc(idNumber, country, docType);
  
  return {
    valid: isValid,
    message: isValid ? 'Valid document' : 'Invalid document number'
  };
}

// Usage in a form
const result = validateUserIdDocument('12345678Z', 'ES', 'nif');
console.log(result); // { valid: true, message: 'Valid document' }

Business Registration Validation

const { isValidVat, isValidViesVat } = require('universal-id-validator');

async function validateBusinessVat(vatNumber, country) {
  // First, do a format validation (offline, fast)
  const formatValid = isValidVat(vatNumber);
  
  if (!formatValid) {
    return { valid: false, message: 'Invalid VAT format' };
  }

  // For EU countries, verify with VIES API (online, slower)
  if (['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 
       'FR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 
       'PL', 'PT', 'RO', 'SE', 'SK', 'SL'].includes(country)) {
    try {
      const viesResult = await isValidViesVat(
        vatNumber.substring(2), // Remove country code
        country
      );
      
      return {
        valid: viesResult.isValid,
        message: viesResult.isValid ? 'VAT verified' : 'VAT not found in VIES',
        viesData: viesResult
      };
    } catch (error) {
      // Fallback to format validation if VIES is unavailable
      return { valid: formatValid, message: 'Format valid, VIES unavailable' };
    }
  }

  return { valid: true, message: 'Format valid' };
}

Dynamic Country Selection

const { supportedCountriesIdDoc, supportedIdDocsByCountry } = require('universal-id-validator');

// Get all countries for dropdown
const countries = supportedCountriesIdDoc();

// When user selects a country, show available document types
function getDocumentTypesForCountry(country) {
  const docTypes = supportedIdDocsByCountry(country);
  
  // Map to friendly names
  const friendlyNames = {
    'passport': 'Passport',
    'nif': 'NIF (Tax ID)',
    'nie': 'NIE (Foreigner ID)',
    'cc': 'CC (Citizen Card)',
    'gic': 'Identity Card',
    'cf': 'Codice Fiscale',
    'cni': 'Carte Nationale d\'Identité'
  };

  return docTypes.map(type => ({
    value: type,
    label: friendlyNames[type] || type.toUpperCase()
  }));
}

console.log(getDocumentTypesForCountry('ES'));
// [
//   { value: 'nif', label: 'NIF (Tax ID)' },
//   { value: 'nie', label: 'NIE (Foreigner ID)' },
//   { value: 'passport', label: 'Passport' }
// ]

⚠️ Important Notes

  • Country Codes: Use ISO 3166-1 alpha-2 country codes (e.g., "ES", "FR", "DE")
  • Document Type: Document type parameter is case-insensitive (e.g., "nif", "NIF", "Nif" all work)
  • VAT Country Codes: Most VAT numbers use the same country code, except Greece (use "EL" instead of "GR") and Slovenia (use "SI" instead of "SL")
  • VIES API: The European Commission's VIES API has rate limits and may be unavailable at times. Use it sparingly and implement fallback logic.
  • Validation Type: This library validates the format and checksum of documents, not their actual existence or validity in official databases (except when using isValidViesVat)

Supported Countries

  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • CNI (Carte Nationale d'Identité)
  • Passport
  • VAT (Value Added Tax ID)
  • GIC (German Identity Card)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID) (country code: EL)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • CF (Codice Fiscale)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • CC (Cartão de Cidadão)
  • NIF (Número de Identificação Fiscal)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • DNI/NIF (Documento Nacional de Identidad / Número de Identificación Fiscal)
  • NIE (Número de Identificación de Extranjero)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID) (country code: SI)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport
  • VAT (Value Added Tax ID)
  • Passport

Details

isValidIdDoc

To validate personal identification documents, use the isValidIdDoc function. It takes three parameters:

  • idDoc (string): The identification document number to validate.
  • country (string): The alpha-2 country code following ISO 3166-1 (e.g., "ES" for Spain, "FR" for France).
  • idDocType (string, optional): The type of identification document to validate. For a list of supported identification document types, please refer to the expanded view of the Supported Countries (to validate VAT, use isValidVat). If this parameter is not passed, the function will check if the passed id doc is valid for any of the supported id docs for the country.

isValidVat

To validate any VAT number from the list of Supported Countries, use the isValidVat function. It takes one parameter:

  • vatNumber (string): The VAT number to validate. Should include the VAT country code. In most cases it coincides with the alpha-2 country code, with some exceptions (e.g., "EL" for Greece instead of "GR").

isValidViesVat

To validate a VAT number for an EU member state, use the isValidViesVat function. This function uses the API provided by the European Commission to validate the VAT number. It takes two parameters:

  • vatNumber (string): The VAT number to validate. Should not include the country code.
  • countryCode (string): The alpha-2 country code following ISO 3166-1 (e.g., "ES" for Spain, "FR" for France).

It returns an object with the following properties:

  • isValid (boolean): Whether the VAT number is valid or not.
  • userError (boolean): The error returned by the VIES API. If the request was successful, it will equal 'VALID' or 'INVALID'. If the request was not successful, it will return a string with the error code.
  • vatNumber (string): The VAT number actually validated. For example, if the passed VAT number is "ES12345678", the returned VAT number will be "12345678", without the country code.

Please note that the VIES API is very limited in the number of requests it can handle. Please use moderately and expect the service to be unavailable at times.

supportedIdDocsByCountry

To get a list of supported identification documents for a country, use the supportedIdDocsByCountry function. It takes one parameter:

  • country (string): The alpha-2 country code following ISO 3166-1 (e.g., "ES" for Spain, "FR" for France).

It returns an array of strings with the supported identification documents for the country.

supportedCountriesIdDoc

To get a list of supported countries for identification documents (not VAT), use the supportedCountriesIdDoc function. It takes no parameters.

It returns an array of strings with the supported countries.

supportedCountriesVat

To get a list of supported countries for VAT validation, use the supportedCountriesVat function. It takes no parameters.

It returns an array of strings with the supported VAT country codes for VAT validation.

Resources