@nibble-codes/id-checksum
Version:
A comprehensive library for generating and validating various types of identification numbers
229 lines (169 loc) โข 7.82 kB
Markdown
# Universal ID Validator
A comprehensive, extensible JavaScript library for generating and validating various types of identification numbers from around the world, following SOLID, DRY, and KISS principles.
## ๐ Features
- **19 ID Types**: Support for identification numbers from 15+ countries/regions
- **Validation & Generation**: Both validate existing IDs and generate valid ones
- **Auto-detection**: Automatically detect ID type from format
- **TypeScript Ready**: Full TypeScript support with type definitions
- **Extensible**: Easy to add new ID types following established patterns
- **Well-tested**: Comprehensive test suite with high coverage
- **Clean Architecture**: Follows SOLID, DRY, KISS principles
- **Tree-shakeable**: Import only what you need
## ๐ฆ Installation
```bash
npm install universal-id-validator
```
## ๐ง Quick Start
```javascript
import UniversalIdValidator from 'universal-id-validator';
const validator = new UniversalIdValidator();
// Validate with explicit type
const result = validator.validate('A1234560', 'HKID');
console.log(result.isValid); // true/false
console.log(result.message); // Validation message
// Auto-detect and validate
const autoResult = validator.validate('A1234560');
console.log(autoResult.isValid);
// Generate valid ID
const newHkid = validator.generate('HKID');
console.log(newHkid); // e.g., "B7654321"
// Detect ID type
const type = validator.detectType('A1234567');
console.log(type); // "HKID"
```
## ๐ Supported ID Types
| Type | Country/Region | Description | Format | Example |
|------|----------------|-------------|--------|---------|
| **HKID** | ๐ญ๐ฐ Hong Kong | Identity Card | 1-2 letters + 6 digits + check char | A1234560 |
| **TWID** | ๐น๐ผ Taiwan | Identity Card | Letter + 1/2 + 8 digits | A123456789 |
| **AADHAAR** | ๐ฎ๐ณ India | Aadhaar Card | 12 digits | 123456789012 |
| **PAN** | ๐ฎ๐ณ India | Permanent Account Number | 5 letters + 4 digits + 1 letter | ABCDE1234F |
| **NRIC** | ๐ธ๐ฌ Singapore | National Registration IC | S/T + 7 digits + letter | S1234567A |
| **FIN** | ๐ธ๐ฌ Singapore | Foreign Identification Number | F/G + 7 digits + letter | F1234567A |
| **SSN** | ๐บ๐ธ United States | Social Security Number | XXX-XX-XXXX | 123-45-6789 |
| **SIN** | ๐จ๐ฆ Canada | Social Insurance Number | XXX XXX XXX | 123 456 789 |
| **NINO** | ๐ฌ๐ง United Kingdom | National Insurance Number | 2 letters + 6 digits + letter | AB123456C |
| **BSN** | ๐ณ๐ฑ Netherlands | Burgerservicenummer | 9 digits | 123456789 |
| **CPF** | ๐ง๐ท Brazil | Cadastro de Pessoas Fรญsicas | XXX.XXX.XXX-XX | 123.456.789-01 |
| **RUT** | ๐จ๐ฑ Chile | Rol รnico Tributario | XX.XXX.XXX-X | 12.345.678-9 |
| **CUIL** | ๐ฆ๐ท Argentina | Cรณdigo รnico de Identificaciรณn | XX-XXXXXXXX-X | 20-12345678-9 |
| **RFC** | ๐ฒ๐ฝ Mexico | Registro Federal de Contribuyentes | 3-4 letters + 6 digits + 3 chars | ABC123456DEF |
| **PERSONNUMMER** | ๐ธ๐ช Sweden | Personal Identity Number | YYMMDD-XXXX | 901201-1234 |
| **PERSONALNUMMER** | ๐ณ๐ด Norway | Personal Identity Number | 11 digits | 12345678901 |
| **CPR** | ๐ฉ๐ฐ Denmark | Central Person Register | DDMMYY-XXXX | 120190-1234 |
| **PESEL** | ๐ต๐ฑ Poland | Powszechny Elektroniczny System | 11 digits | 90120112345 |
| **CNP** | ๐ท๐ด Romania | Cod Numeric Personal | 13 digits | 1901201123456 |
## ๐๏ธ Architecture
The library follows clean architecture principles:
### Core Components
- **UniversalIdValidator**: Main facade class (KISS principle)
- **BaseValidator**: Template method pattern for consistent validation
- **ValidatorFactory**: Factory pattern for creating validators (Open/Closed)
- **GeneratorFactory**: Factory pattern for creating generators
- **IdDetector**: Strategy pattern for ID type detection
- **ChecksumCalculator**: Utility class for checksum algorithms (Single Responsibility)
### Design Principles Applied
#### SOLID Principles
- **S**ingle Responsibility: Each class has one reason to change
- **O**pen/Closed: Easy to extend with new ID types without modifying existing code
- **L**iskov Substitution: All validators are interchangeable
- **I**nterface Segregation: Minimal, focused interfaces
- **D**ependency Inversion: Depend on abstractions, not concretions
#### DRY (Don't Repeat Yourself)
- Common validation logic in BaseValidator
- Shared checksum algorithms in ChecksumCalculator
- Reusable helper methods
#### KISS (Keep It Simple, Stupid)
- Simple, intuitive API
- Clear method names and purposes
- Minimal configuration required
## ๐ Advanced Usage
### Direct Validator Access
```javascript
import { HkidValidator, TwidValidator } from 'universal-id-validator/validators';
const hkidValidator = new HkidValidator();
const result = hkidValidator.validate('A1234560');
```
### Custom Validators
```javascript
import { ValidatorFactory, BaseValidator } from 'universal-id-validator';
class CustomValidator extends BaseValidator {
validateFormat(id) {
// Your format validation logic
}
validateChecksum(id) {
// Your checksum validation logic
}
}
const factory = new ValidatorFactory();
factory.register('CUSTOM', CustomValidator);
```
### Generation Options
```javascript
// HKID with double prefix
const hkid = validator.generate('HKID', { doublePrefix: true });
// TWID with specific gender
const twid = validator.generate('TWID', { gender: 1 }); // 1=male, 2=female
// PAN for specific entity type
const pan = validator.generate('PAN', { entityType: 'C' }); // Company
// SSN with formatting
const ssn = validator.generate('SSN', { formatted: true }); // XXX-XX-XXXX
// NRIC with birth year
const nric = validator.generate('NRIC', { birthYear: 1990 });
```
### Entity Type Detection (PAN)
```javascript
import { PanValidator } from 'universal-id-validator/validators';
const panValidator = new PanValidator();
const entityType = panValidator.getEntityType('ABCPE1234F');
console.log(entityType); // "Individual"
```
## ๐งช Testing
```bash
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # Coverage report
```
## ๐ Validation Results
All validation methods return a `ValidationResult` object:
```javascript
{
isValid: boolean, // Whether the ID is valid
message: string, // Human-readable message
details: object // Additional validation details
}
```
## ๐ Regional Coverage
- **Asia-Pacific**: Hong Kong, Taiwan, India, Singapore
- **North America**: United States, Canada
- **Europe**: United Kingdom, Netherlands, Sweden, Norway, Denmark, Poland, Romania
- **South America**: Brazil, Chile, Argentina
- **Central America**: Mexico
## ๐ค Contributing
We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines on:
- Setting up the development environment
- Adding new ID types
- Running tests and builds
- Publishing to NPM
### Adding New ID Types
1. Create validator class extending `BaseValidator`
2. Create generator class extending `BaseGenerator`
3. Add checksum algorithm to `ChecksumCalculator`
4. Register in factories
5. Add detection pattern to `IdDetector`
6. Write comprehensive tests
## ๐ License
MIT License - see [LICENSE](LICENSE) file for details.
## ๐ Links
- [GitHub Repository](https://github.com/yourusername/universal-id-validator)
- [NPM Package](https://www.npmjs.com/package/universal-id-validator)
- [Contributing Guide](CONTRIBUTING.md)
- [Changelog](CHANGELOG.md)
## ๐ Stats
- **19 ID Types** supported
- **15+ Countries/Regions** covered
- **100% Test Coverage** maintained
- **Tree-shakeable** for optimal bundle size
- **TypeScript** definitions included
---
Built with โค๏ธ following clean code principles and international standards.