Skip to content

Instantly share code, notes, and snippets.

@paoloconi96
Created November 8, 2022 13:20
Show Gist options
  • Save paoloconi96/82ae9cdbed19316886124ba25c6955de to your computer and use it in GitHub Desktop.
Save paoloconi96/82ae9cdbed19316886124ba25c6955de to your computer and use it in GitHub Desktop.
Simple PHP method to validate vatNumbers for a limited number of extra-EU and all the EU countries
private const COUNTRY_VALIDATION_PATTERNS = [
'AL' => '[JKL]\d{8}[A-Z]',
'AT' => 'U[\d]{8}',
'AU' => '\d{11}',
'BE' => '\d{10}',
'BG' => '\d{9,10}',
'BY' => '\d{9}',
'CA' => '\d{9}',
'CH' => '\d{3}\.\d{3}\.\d{3}',
'CY' => '\d{8}[A-Z]',
'CZ' => '\d{8,10}',
'DE' => '\d{9}',
'DK' => '\d{8}',
'EE' => '\d{9}',
'EL' => '\d{9}',
'ES' => '([A-Z]\d{7}[A-Z]|\d{8}[A-Z]|[A-Z]\d{8})',
'FI' => '\d{8}',
'FR' => '[A-HJ-NP-Z\d]{2}\d{9}',
'GB' => '(\d{9}|\d{12}|(GD|HA)\d{3})',
'HR' => '\d{11}',
'HU' => '\d{8}',
'IE' => '(\d{7}[A-Z]|\d[A-Z]\d{5}[A-Z]|\d{7}[A-Z]{2})',
'ID' => '\d{2}\.\d{3}\.\d{3}\.\d-\d{3}\.\d{3}',
'IL' => '\d{9}',
'IN' => '\d{15}',
'IS' => '\d{5,6}',
'IT' => '\d{11}',
'KZ' => '\d{12}',
'LT' => '(\d{9}|\d{12})',
'LU' => '\d{8}',
'LV' => '\d{11}',
'MK' => '\d{13}',
'MT' => '\d{8}',
'NG' => '\d{8}-\d{4}',
'NL' => '\d{9}B\d{2}',
'NO' => '\d{9}MVA',
'NZ' => '\d{9}',
'PH' => '\d{12}',
'PL' => '\d{10}',
'PT' => '\d{9}',
'RO' => '\d{2,10}',
'RS' => '\d{9}',
'RU' => '\d{10}',
'SA' => '\d{15}',
'SE' => '\d{12}',
'SI' => '\d{8}',
'SK' => '\d{10}',
'SM' => '\d{5}',
'TR' => '\d{10}',
'UA' => '\d{12}',
'UZ' => '2\d{7}[A-Z]',
];
public static function isValid(string $countryCode, string $identifier): bool
{
$vatNumber = str_replace(' ', '', strtoupper($vatNumber));
if (!array_key_exists($countryCode, self::COUNTRY_VALIDATION_PATTERNS)) {
return false;
}
return preg_match('/^' . self::COUNTRY_VALIDATION_PATTERNS[$countryCode] . '$/', $identifier) > 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment