JSPM

global-regex-validator

1.0.7
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 11
  • Score
    100M100P100Q45330F
  • License MIT

A comprehensive regex validator library for global VAT numbers and other validation patterns

Package Exports

  • global-regex-validator

Readme

global-regex-validator

A comprehensive, framework-agnostic regex validator library for global VAT (Value Added Tax) numbers and other validation patterns. Works seamlessly in Node.js, browsers, and any JavaScript/TypeScript environment.

Features

  • 🌍 Global Coverage: Supports VAT validation for 60+ countries
  • 🔧 Framework-Agnostic: Works with React, Vue, Angular, Svelte, Node.js, and vanilla JavaScript
  • 📦 Tree-Shakeable: Zero dependencies, optimized for bundle size
  • 🎯 TypeScript: Full TypeScript support with type definitions
  • Universal: Compatible with ESM and CommonJS module systems
  • 🚀 Lightweight: Small bundle size, no external dependencies

Installation

npm install global-regex-validator
yarn add global-regex-validator
pnpm add global-regex-validator

Usage

ES Modules (ESM)

import isVAT from 'global-regex-validator';
// or
import { isVAT, vatMatchers } from 'global-regex-validator';

// Validate a VAT number
const isValid = isVAT('DE123456789', 'DE');
console.log(isValid); // true or false

CommonJS (CJS)

const isVAT = require('global-regex-validator').default;
// or
const { isVAT, vatMatchers } = require('global-regex-validator');

const isValid = isVAT('DE123456789', 'DE');
console.log(isValid); // true or false

Framework Examples

React

import React, { useState } from 'react';
import isVAT from 'global-regex-validator';

function VATValidator() {
  const [vatNumber, setVatNumber] = useState('');
  const [country, setCountry] = useState('DE');
  const [isValid, setIsValid] = useState(null);

  const validate = () => {
    try {
      setIsValid(isVAT(vatNumber, country));
    } catch (error) {
      setIsValid(false);
    }
  };

  return (
    <div>
      <input 
        value={vatNumber} 
        onChange={(e) => setVatNumber(e.target.value)} 
        placeholder="VAT Number"
      />
      <select value={country} onChange={(e) => setCountry(e.target.value)}>
        <option value="DE">Germany</option>
        <option value="FR">France</option>
        <option value="GB">United Kingdom</option>
      </select>
      <button onClick={validate}>Validate</button>
      {isValid !== null && (
        <p>{isValid ? 'Valid' : 'Invalid'} VAT number</p>
      )}
    </div>
  );
}

Vue

<template>
  <div>
    <input v-model="vatNumber" placeholder="VAT Number" />
    <select v-model="country">
      <option value="DE">Germany</option>
      <option value="FR">France</option>
      <option value="GB">United Kingdom</option>
    </select>
    <button @click="validate">Validate</button>
    <p v-if="isValid !== null">
      {{ isValid ? 'Valid' : 'Invalid' }} VAT number
    </p>
  </div>
</template>

<script>
import isVAT from 'global-regex-validator';

export default {
  data() {
    return {
      vatNumber: '',
      country: 'DE',
      isValid: null
    };
  },
  methods: {
    validate() {
      try {
        this.isValid = isVAT(this.vatNumber, this.country);
      } catch (error) {
        this.isValid = false;
      }
    }
  }
};
</script>

Node.js

import isVAT from 'global-regex-validator';

// Validate VAT numbers in your API
app.post('/validate-vat', (req, res) => {
  const { vatNumber, countryCode } = req.body;
  
  try {
    const isValid = isVAT(vatNumber, countryCode);
    res.json({ valid: isValid });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

Custom Country Validators

import { addCustomVATMatchers, isVAT } from 'global-regex-validator';

// Add support for custom countries
addCustomVATMatchers({
  'MY': (str) => /^MY\d{10}$/.test(str), // Malaysia
  'TH': (str) => /^TH\d{13}$/.test(str), // Thailand
});

// Now validate with your custom countries
isVAT('MY1234567890', 'MY'); // true
isVAT('TH1234567890123', 'TH'); // true

// Or use inline custom matchers (without modifying global matchers)
isVAT('XX12345678', 'XX', {
  'XX': (str) => /^XX\d{8}$/.test(str)
}); // true

API

isVAT(vatNumber: string, countryCode: string, customMatchers?: Record<string, VATMatcher>): boolean

Validates a VAT number for a specific country.

Parameters:

  • vatNumber (string): The VAT number to validate
  • countryCode (string): ISO 3166-1 alpha-2 country code (e.g., 'DE', 'FR', 'GB')
  • customMatchers (optional): Object with custom country validators to use for this validation only

Returns:

  • boolean: true if the VAT number is valid, false otherwise

Throws:

  • TypeError: If input is not a string
  • Error: If country code is not supported

Example:

isVAT('DE123456789', 'DE'); // true
isVAT('FR12345678901', 'FR'); // true
isVAT('INVALID', 'DE'); // false
isVAT('DE123456789', 'XX'); // throws Error: Invalid country code: 'XX'

// Using custom matchers inline
isVAT('XX12345678', 'XX', {
  'XX': (str) => /^XX\d{8}$/.test(str)
}); // true

addCustomVATMatchers(customMatchers: Record<string, VATMatcher>): void

Adds custom VAT matchers to the global matchers object. These matchers will be available for all subsequent isVAT calls.

Parameters:

  • customMatchers (object): Object with country codes as keys and validator functions as values

Example:

import { addCustomVATMatchers } from 'global-regex-validator';

// Add custom country validators
addCustomVATMatchers({
  'XX': (str) => /^XX\d{8}$/.test(str),
  'YY': (str) => /^YY[A-Z0-9]{10}$/.test(str),
  'ZZ': (str) => {
    // Custom validation logic with checksum
    if (!/^ZZ\d{9}$/.test(str)) return false;
    // Add your custom validation logic here
    return true;
  }
});

// Now you can use these country codes
isVAT('XX12345678', 'XX'); // true
isVAT('YYABC1234567', 'YY'); // true

vatMatchers: Record<string, (str: string) => boolean>

An object containing all available VAT matcher functions for each country. You can use this to access individual country validators directly.

Example:

import { vatMatchers } from 'global-regex-validator';

// Use a specific country validator
const isValidGermanVAT = vatMatchers.DE('123456789');
const isValidFrenchVAT = vatMatchers.FR('FR12345678901');

Custom VAT Matchers

You can add support for additional countries by providing custom regex validators. This is useful when you need to validate VAT numbers for countries not included in the built-in list.

Adding Custom Matchers Globally

Use addCustomVATMatchers to add custom validators that will be available throughout your application:

import { addCustomVATMatchers, isVAT } from 'global-regex-validator';

// Add custom validators
addCustomVATMatchers({
  'MY': (str) => /^MY\d{10}$/.test(str), // Malaysia
  'TH': (str) => /^TH\d{13}$/.test(str), // Thailand
});

// Use them anywhere in your app
isVAT('MY1234567890', 'MY'); // true
isVAT('TH1234567890123', 'TH'); // true

Using Custom Matchers Inline

You can also pass custom matchers directly to the isVAT function without modifying the global matchers:

import isVAT from 'global-regex-validator';

// Validate with custom matcher (only for this call)
const isValid = isVAT('XX12345678', 'XX', {
  'XX': (str) => /^XX\d{8}$/.test(str)
});

Advanced Custom Validators

You can create complex validators with custom logic, checksums, or additional validation:

import { addCustomVATMatchers } from 'global-regex-validator';

addCustomVATMatchers({
  'CUSTOM': (str) => {
    // Basic format check
    if (!/^CUSTOM\d{8}$/.test(str)) return false;
    
    // Extract digits
    const digits = str.replace('CUSTOM', '').split('').map(Number);
    
    // Custom checksum validation
    const sum = digits.slice(0, 7).reduce((acc, d, i) => acc + d * (i + 1), 0);
    const checkDigit = sum % 11;
    
    return checkDigit === digits[7];
  }
});

TypeScript Support for Custom Matchers

import { addCustomVATMatchers, isVAT, VATMatcher } from 'global-regex-validator';

// Type-safe custom matchers using the exported VATMatcher type
const customMatchers: Record<string, VATMatcher> = {
  'XX': (str: string) => /^XX\d{8}$/.test(str),
  'YY': (str: string) => /^YY[A-Z0-9]{10}$/.test(str),
};

addCustomVATMatchers(customMatchers);

// Or use inline
const isValid = isVAT('XX12345678', 'XX', customMatchers);

Supported Countries

European Union

AT (Austria), BE (Belgium), BG (Bulgaria), HR (Croatia), CY (Cyprus), CZ (Czech Republic), DK (Denmark), EE (Estonia), FI (Finland), FR (France), DE (Germany), EL (Greece), HU (Hungary), IE (Ireland), IT (Italy), LV (Latvia), LT (Lithuania), LU (Luxembourg), MT (Malta), NL (Netherlands), PL (Poland), PT (Portugal), RO (Romania), SK (Slovakia), SI (Slovenia), ES (Spain), SE (Sweden)

Non-EU Countries

AL (Albania), MK (North Macedonia), AU (Australia), BY (Belarus), CA (Canada), IS (Iceland), IN (India), ID (Indonesia), IL (Israel), KZ (Kazakhstan), NZ (New Zealand), NG (Nigeria), NO (Norway), PH (Philippines), RU (Russia), SM (San Marino), SA (Saudi Arabia), RS (Serbia), CH (Switzerland), TR (Turkey), UA (Ukraine), GB (United Kingdom), UZ (Uzbekistan)

Latin America

AR (Argentina), BO (Bolivia), BR (Brazil), CL (Chile), CO (Colombia), CR (Costa Rica), EC (Ecuador), SV (El Salvador), GT (Guatemala), HN (Honduras), MX (Mexico), NI (Nicaragua), PA (Panama), PY (Paraguay), PE (Peru), DO (Dominican Republic), UY (Uruguay), VE (Venezuela)

TypeScript Support

Full TypeScript support is included:

import isVAT, { vatMatchers, VATMatcher } from 'global-regex-validator';

// Type-safe usage
const isValid: boolean = isVAT('DE123456789', 'DE');
const germanValidator: VATMatcher = vatMatchers.DE;

Browser Support

Works in all modern browsers that support ES2020:

  • Chrome/Edge (latest)
  • Firefox (latest)
  • Safari (latest)
  • Opera (latest)

Node.js Support

Requires Node.js >= 14.0.0

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Author

Created with ❤️ for the global developer community.