Package Exports
- idnumbers
- idnumbers/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (idnumbers) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
idnumbers
A comprehensive TypeScript/JavaScript library for validating and parsing national identification numbers from 80 countries across 6 continents.
Features
- โ 80 countries supported - Comprehensive coverage across all continents
- ๐ Validation - Verify ID number format and checksums
- ๐ Parsing - Extract information like birth date, gender, and citizenship
- ๐ก๏ธ Type-safe - Full TypeScript support with type definitions
- ๐ฆ Zero dependencies - Lightweight and secure
- โจ Well-tested - Comprehensive test coverage with 100% pass rate
- ๐ Multiple formats - Supports various ID number formats per country
Installation
npm install idnumbersyarn add idnumberspnpm add idnumbersQuick Start
import { validateNationalId, parseIdInfo } from 'idnumbers';
// Validate a US Social Security Number
const result = validateNationalId('USA', '123-45-6789');
console.log(result.isValid); // true or false
// Parse information from a South African ID
const info = parseIdInfo('ZAF', '8001015009087');
console.log(info);
// {
// yyyymmdd: Date(1980-01-01),
// gender: 'male',
// citizenship: 'citizen',
// ...
// }API Reference
validateNationalId(countryCode, idNumber)
Validates a national ID number for a specific country.
Parameters:
countryCode(string): ISO 3166-1 alpha-3 country code (e.g., 'USA', 'GBR', 'FRA')idNumber(string): The ID number to validate
Returns: ValidationResult
{
isValid: boolean;
countryCode: string;
idNumber: string;
extractedInfo?: any;
errorMessage?: string;
}Example:
const result = validateNationalId('GBR', 'AB123456C');
if (result.isValid) {
console.log('Valid UK National Insurance Number');
} else {
console.log('Invalid:', result.errorMessage);
}parseIdInfo(countryCode, idNumber)
Extracts information from a national ID number (if supported by the country).
Parameters:
countryCode(string): ISO 3166-1 alpha-3 country codeidNumber(string): The ID number to parse
Returns: ParsedInfo | null
The returned object varies by country but commonly includes:
yyyymmddorbirthDate: Date of birthgender: 'male' or 'female'citizenship: 'citizen' or 'resident'locationorregion: Geographic information- Additional country-specific fields
Example:
const info = parseIdInfo('SWE', '811218-9876');
console.log(info);
// {
// yyyymmdd: Date(1981-12-18),
// gender: 'male',
// ...
// }validateMultipleIds(ids)
Validates multiple ID numbers in batch.
Parameters:
ids(Array): Array of objects withcountryCodeandidNumber
Returns: Array of ValidationResult
Example:
const results = validateMultipleIds([
{ countryCode: 'USA', idNumber: '123-45-6789' },
{ countryCode: 'GBR', idNumber: 'AB123456C' },
{ countryCode: 'FRA', idNumber: '255081416802538' }
]);
results.forEach(result => {
console.log(`${result.countryCode}: ${result.isValid}`);
});listSupportedCountries()
Returns a list of all supported countries.
Returns: Array of country information
[
{
code: 'USA',
name: 'United States',
idType: 'Social Security Number'
},
...
]Example:
const countries = listSupportedCountries();
console.log(`Supports ${countries.length} countries`);getCountryIdFormat(countryCode)
Gets format information for a country's ID number.
Parameters:
countryCode(string): ISO 3166-1 alpha-3 country code
Returns: Format information or null
Example:
const format = getCountryIdFormat('IND');
console.log(format);
// {
// countryCode: 'IND',
// format: 'XXXX XXXX XXXX',
// length: { min: 12, max: 12 },
// ...
// }Supported Countries
North America (3)
- ๐บ๐ธ USA - Social Security Number (SSN)
- ๐จ๐ฆ CAN - Social Insurance Number (SIN)
- ๐ฒ๐ฝ MEX - CURP (Clave รnica de Registro de Poblaciรณn)
South America (4)
- ๐ฆ๐ท ARG - DNI (Documento Nacional de Identidad)
- ๐ง๐ท BRA - CPF (Cadastro de Pessoas Fรญsicas)
- ๐จ๐ฑ CHL - RUT/RUN (Rol รnico Tributario)
- ๐ป๐ช VEN - Cรฉdula de Identidad
Europe (38)
- ๐ฆ๐ฑ ALB - National ID Number
- ๐ฆ๐น AUT - Social Security Number
- ๐ง๐ช BEL - National Register Number
- ๐ง๐ฆ BIH - JMBG (Unique Master Citizen Number)
- ๐ง๐ฌ BGR - Personal Number (EGN)
- ๐ญ๐ท HRV - Personal Identification Number (OIB)
- ๐จ๐พ CYP - Tax Identification Number
- ๐จ๐ฟ CZE - Birth Number
- ๐ฉ๐ฐ DNK - CPR Number
- ๐ช๐ช EST - Personal Identification Code
- ๐ซ๐ฎ FIN - Personal Identity Code (HETU)
- ๐ซ๐ท FRA - Social Security Number (NIR)
- ๐ฉ๐ช DEU - Tax ID (Steueridentifikationsnummer)
- ๐ฌ๐ท GRC - Tax Registration Number (AFM)
- ๐ญ๐บ HUN - Tax Number
- ๐ฎ๐ธ ISL - National ID (Kennitala)
- ๐ฎ๐ช IRL - Personal Public Service Number (PPS)
- ๐ฎ๐น ITA - Fiscal Code (Codice Fiscale)
- ๐ฑ๐ป LVA - Personal Code
- ๐ฑ๐น LTU - Personal Code
- ๐ฑ๐บ LUX - National ID Number
- ๐ฒ๐ฐ MKD - JMBG (Unique Master Citizen Number)
- ๐ฒ๐ช MNE - JMBG (Unique Master Citizen Number)
- ๐ณ๐ฑ NLD - BSN (Burgerservicenummer)
- ๐ณ๐ด NOR - National Identity Number
- ๐ต๐ฑ POL - PESEL
- ๐ต๐น PRT - NIF (Nรบmero de Identificaรงรฃo Fiscal)
- ๐ท๐ด ROU - Personal Numerical Code (CNP)
- ๐ท๐บ RUS - Internal Passport
- ๐ท๐ธ SRB - JMBG (Unique Master Citizen Number)
- ๐ธ๐ฐ SVK - Birth Number
- ๐ธ๐ฎ SVN - Personal Number (EMล O)
- ๐ช๐ธ ESP - DNI/NIE
- ๐ธ๐ช SWE - Personal Identity Number (Personnummer)
- ๐จ๐ญ CHE - Social Security Number (AHV-Nr)
- ๐น๐ท TUR - TC Kimlik No
- ๐บ๐ฆ UKR - Tax Number (RNTRC)
- ๐ฌ๐ง GBR - National Insurance Number (NINO)
Asia (18)
- ๐ง๐ญ BHR - Personal Number (CPR)
- ๐ง๐ฉ BGD - National ID
- ๐จ๐ณ CHN - Resident Identity Card
- ๐ฌ๐ช GEO - Personal Number
- ๐ญ๐ฐ HKG - Hong Kong Identity Card
- ๐ฎ๐ณ IND - Aadhaar
- ๐ฎ๐ฉ IDN - NIK (Nomor Induk Kependudukan)
- ๐ฏ๐ต JPN - My Number
- ๐ฐ๐ฟ KAZ - Individual Identification Number (IIN)
- ๐ฐ๐ท KOR - Resident Registration Number
- ๐ฐ๐ผ KWT - Civil ID
- ๐ฑ๐ฐ LKA - National Identity Card
- ๐ฒ๐พ MYS - MyKad
- ๐ต๐ฐ PAK - CNIC (Computerized National Identity Card)
- ๐ต๐ญ PHL - PhilSys Number
- ๐ธ๐ฆ SAU - National ID
- ๐ธ๐ฌ SGP - NRIC/FIN
- ๐น๐ญ THA - National ID
- ๐น๐ผ TWN - National Identification Card
- ๐ป๐ณ VNM - Citizen Identity Card
Africa (3)
- ๐ณ๐ฌ NGA - National Identification Number (NIN)
- ๐ฟ๐ฆ ZAF - ID Number
- ๐ฟ๐ผ ZWE - National ID
Oceania (2)
- ๐ฆ๐บ AUS - Medicare Number
- ๐ณ๐ฟ NZL - Driver License Number
Middle East (Additional)
- ๐ฆ๐ช ARE - Emirates ID
- ๐ฎ๐ฑ ISR - ID Number (Teudat Zehut)
Usage Examples
Basic Validation
import { validateNationalId } from 'idnumbers';
// US Social Security Number
const usa = validateNationalId('USA', '123-45-6789');
console.log(usa.isValid); // true
// UK National Insurance Number
const uk = validateNationalId('GBR', 'AB123456C');
console.log(uk.isValid); // true
// French Social Security Number
const france = validateNationalId('FRA', '255081416802538');
console.log(france.isValid); // trueParsing Information
import { parseIdInfo } from 'idnumbers';
// South Africa - Extract birth date, gender, citizenship
const zaf = parseIdInfo('ZAF', '8001015009087');
console.log(zaf);
// {
// yyyymmdd: Date(1980-01-01),
// gender: 'male',
// citizenship: 'citizen'
// }
// Sweden - Extract birth date and gender
const swe = parseIdInfo('SWE', '811218-9876');
console.log(swe);
// {
// yyyymmdd: Date(1981-12-18),
// gender: 'male'
// }
// China - Extract birth date, province, and gender
const chn = parseIdInfo('CHN', '11010219840406970X');
console.log(chn);
// {
// birthDate: Date(1984-04-06),
// province: 'Beijing',
// gender: 'male'
// }Batch Validation
import { validateMultipleIds } from 'idnumbers';
const ids = [
{ countryCode: 'USA', idNumber: '123-45-6789' },
{ countryCode: 'GBR', idNumber: 'AB123456C' },
{ countryCode: 'JPN', idNumber: '123456789012' },
{ countryCode: 'XXX', idNumber: '123' } // Invalid country
];
const results = validateMultipleIds(ids);
results.forEach((result, index) => {
console.log(`ID ${index + 1}: ${result.isValid ? 'Valid' : 'Invalid'}`);
if (!result.isValid) {
console.log(` Error: ${result.errorMessage}`);
}
});Error Handling
import { validateNationalId } from 'idnumbers';
const result = validateNationalId('USA', '000-45-6789');
if (!result.isValid) {
console.log('Validation failed:', result.errorMessage);
// "Validation failed: Invalid SSN - forbidden prefix 000"
}
// Unsupported country
const invalid = validateNationalId('XXX', '123456789');
console.log(invalid.errorMessage);
// "Unsupported country code: XXX"TypeScript Usage
import { validateNationalId, parseIdInfo, ValidationResult } from 'idnumbers';
// Type-safe validation
const result: ValidationResult = validateNationalId('USA', '123-45-6789');
if (result.isValid && result.extractedInfo) {
// extractedInfo is typed based on the country
console.log('Valid ID with extracted info:', result.extractedInfo);
}
// Type-safe parsing
const info = parseIdInfo('ZAF', '8001015009087');
if (info) {
// TypeScript knows the possible fields
console.log('Birth date:', info.yyyymmdd);
console.log('Gender:', info.gender);
}Integration with Forms
import { validateNationalId } from 'idnumbers';
function validateUserID(country: string, idNumber: string): {
valid: boolean;
message: string;
} {
const result = validateNationalId(country, idNumber);
return {
valid: result.isValid,
message: result.isValid
? 'Valid ID number'
: result.errorMessage || 'Invalid ID number'
};
}
// In your form handler
const validation = validateUserID('USA', userInput);
if (!validation.valid) {
showError(validation.message);
}Country-Specific Notes
United States (USA)
- Format:
XXX-XX-XXXX(with or without dashes) - Forbidden prefixes:
000,666,900-999 - Example:
123-45-6789
United Kingdom (GBR)
- Format: Two letters, six digits, one letter
- Forbidden prefixes:
BG,GB,NK,KN,TN,NT,ZZ - Example:
AB123456C
China (CHN)
- Format: 18 digits (17 digits + checksum)
- Contains: Region code, birth date, sequence number, checksum
- Checksum can be
X(representing 10) - Example:
11010219840406970X
South Africa (ZAF)
- Format: 13 digits
- Contains: Birth date (YYMMDD), gender, citizenship
- Example:
8001015009087
France (FRA)
- Format: 15 digits (Social Security Number)
- Contains: Gender, year/month of birth, department code
- Example:
255081416802538
Germany (DEU)
- Format: 11 digits (Tax ID)
- Contains: Random number with checksum validation
- Example:
65929970489
Testing
The library includes comprehensive test coverage with 301 tests covering:
- Format validation
- Checksum verification
- Edge cases and error handling
- Information extraction
- Cross-country consistency
Run tests:
npm testRun tests with coverage:
npm run test:coverageContributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
Clone the repository:
git clone https://github.com/identique/idnumbers-npm.git cd idnumbers-npm
Install dependencies:
npm install
This automatically sets up pre-commit hooks via Husky.
Pre-commit Hooks:
The following checks run automatically before each commit:
- โจ Prettier - Code formatting on staged files
- ๐ง TypeScript - Type checking and compilation
- ๐งช Tests - Full test suite
If any check fails, the commit will be blocked until fixed.
Run tests:
npm test # Run all tests npm run test:coverage # Run with coverage report
Build:
npm run build # Compile TypeScript
Linting:
npm run lint # Check for issues npm run lint:fix # Auto-fix issues
License
MIT License - see LICENSE file for details
Changelog
2.1.0
- Added support for 80 countries
- Comprehensive test coverage
- Full TypeScript support
- Enhanced validation and parsing capabilities
Acknowledgments
This library is inspired by and maintains compatibility with validation logic from various national ID systems worldwide.
Support
For issues, questions, or contributions, please visit:
- GitHub: https://github.com/identique/idnumbers-npm
- Issues: https://github.com/identique/idnumbers-npm/issues