-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
624 lines (573 loc) · 16.5 KB
/
index.js
File metadata and controls
624 lines (573 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
/**
* NINO Validator - Validates UK National Insurance Numbers
*
* @fileoverview A comprehensive library for validating, formatting, and parsing
* UK National Insurance Numbers (NINO) according to HMRC rules.
*
* @author Byron Thanopoulos <byron.thanopoulos@gmail.com>
* @version 1.0.0
* @license MIT
* @since 1.0.0
*/
const { getLocalizedMessage } = require('./src/i18n');
/**
* List of invalid prefix combinations for NINO.
* These prefixes are explicitly not used by HMRC and include:
* - Administrative prefixes (BG, GB, NK, KN, TN, NT, ZZ)
* - All combinations starting with D, F, G, I, N, O, Q, U, V
*
* @constant {string[]}
* @readonly
*/
const INVALID_PREFIXES = [
'BG',
'GB',
'NK',
'KN',
'TN',
'NT',
'ZZ',
'DA',
'DB',
'DC',
'DD',
'DE',
'DF',
'DG',
'DH',
'DI',
'DJ',
'DK',
'DL',
'DM',
'DN',
'DO',
'DP',
'DQ',
'DR',
'DS',
'DT',
'DU',
'DV',
'DW',
'DX',
'DY',
'DZ',
'FA',
'FB',
'FC',
'FD',
'FE',
'FF',
'FG',
'FH',
'FI',
'FJ',
'FK',
'FL',
'FM',
'FN',
'FO',
'FP',
'FQ',
'FR',
'FS',
'FT',
'FU',
'FV',
'FW',
'FX',
'FY',
'FZ',
'GA',
'GB',
'GC',
'GD',
'GE',
'GF',
'GG',
'GH',
'GI',
'GJ',
'GK',
'GL',
'GM',
'GN',
'GO',
'GP',
'GQ',
'GR',
'GS',
'GT',
'GU',
'GV',
'GW',
'GX',
'GY',
'GZ',
'NA',
'NB',
'NC',
'ND',
'NE',
'NF',
'NG',
'NH',
'NI',
'NJ',
'NK',
'NL',
'NM',
'NN',
'NO',
'NP',
'NQ',
'NR',
'NS',
'NT',
'NU',
'NV',
'NW',
'NX',
'NY',
'NZ',
'OA',
'OB',
'OC',
'OD',
'OE',
'OF',
'OG',
'OH',
'OI',
'OJ',
'OK',
'OL',
'OM',
'ON',
'OO',
'OP',
'OQ',
'OR',
'OS',
'OT',
'OU',
'OV',
'OW',
'OX',
'OY',
'OZ',
'QQ',
];
/**
* Invalid suffix letters for NINO.
* These letters are not used as suffix characters by HMRC.
*
* @constant {string[]}
* @readonly
*/
const INVALID_SUFFIXES = ['D', 'F', 'I', 'Q', 'U', 'V'];
/**
* @typedef {Object} ValidationOptions
* @property {boolean} [allowSpaces=true] - Allow spaces in the input NINO
* @property {boolean} [requireSuffix=false] - Require the suffix letter to be present
*/
/**
* @typedef {Object} ValidationResult
* @property {boolean} isValid - Whether the NINO is valid
* @property {string|null} error - Detailed error message if invalid, null if valid
* @property {string|null} errorCode - Machine-readable error code for programmatic handling
* @property {string|null} suggestion - Helpful suggestion for fixing the error
*/
/**
* Validates a UK National Insurance Number according to HMRC rules.
*
* This function performs comprehensive validation including:
* - Format validation (2 letters + 6 digits + optional letter)
* - Prefix validation against HMRC invalid list
* - Individual letter validation (first, second, suffix)
* - Number pattern validation (no repeated digits)
*
* @param {string} nino - The NINO to validate
* @param {ValidationOptions} [options={}] - Validation options
* @param {boolean} [options.allowSpaces=true] - Allow spaces in the NINO
* @param {boolean} [options.requireSuffix=false] - Require the suffix letter
*
* @returns {boolean} True if the NINO is valid according to HMRC rules, false otherwise
*
* @example
* // Basic validation
* validateNINO('AB123456C'); // true
* validateNINO('AB123456'); // true (suffix optional)
* validateNINO('invalid'); // false
*
* @example
* // With options
* validateNINO('AB123456', { requireSuffix: true }); // false
* validateNINO('AB 12 34 56 C', { allowSpaces: false }); // false
*
* @example
* // Edge cases
* validateNINO(null); // false
* validateNINO(undefined); // false
* validateNINO(''); // false
* validateNINO('BG123456C'); // false (invalid prefix)
*
* @since 1.0.0
*/
function validateNINO(nino, options = {}) {
// Use the detailed validation and return just the boolean result
const result = validateNINOWithDetails(nino, options);
return result.isValid;
}
/**
* Validates basic input requirements for NINO
* @param {*} nino - Input to validate
* @param {Function} errorResult - Error result factory function
* @returns {Object|null} Error result or null if valid
*/
function validateBasicInput(nino, errorResult) {
if (nino == null) return errorResult('NULL_INPUT');
if (typeof nino !== 'string')
return errorResult('INVALID_TYPE', { type: typeof nino });
if (nino.trim() === '') return errorResult('EMPTY_INPUT');
if (nino.length > 20) return errorResult('INPUT_TOO_LONG');
return null;
}
/**
* Cleans and normalizes NINO input
* @param {string} nino - Raw NINO input
* @param {boolean} allowSpaces - Whether spaces are allowed
* @param {Function} errorResult - Error result factory function
* @returns {Object|string} Error result or cleaned NINO string
*/
function cleanAndNormalizeNino(nino, allowSpaces, errorResult) {
// Check for invalid characters before cleaning
if (!/^[A-Za-z0-9 ]*$/.test(nino)) return errorResult('INVALID_CHARACTERS');
let cleanNino = nino.toUpperCase().trim();
if (!allowSpaces && /\s/.test(cleanNino))
return errorResult('SPACES_NOT_ALLOWED');
if (allowSpaces) cleanNino = cleanNino.replace(/\s/g, '');
// Final check after cleaning
if (!/^[A-Z0-9]*$/.test(cleanNino)) return errorResult('INVALID_CHARACTERS');
return cleanNino;
}
/**
* Validates NINO length requirements
* @param {string} cleanNino - Cleaned NINO string
* @param {Function} errorResult - Error result factory function
* @returns {Object|null} Error result or null if valid
*/
function validateNinoLength(cleanNino, errorResult) {
if (cleanNino.length < 8)
return errorResult('TOO_SHORT', { length: cleanNino.length });
if (cleanNino.length > 9)
return errorResult('TOO_LONG', { length: cleanNino.length });
return null;
}
/**
* Validates NINO component letters against HMRC rules
* @param {string} prefix - Two-letter prefix
* @param {string} suffix - Suffix letter (may be empty)
* @param {Function} errorResult - Error result factory function
* @returns {Object|null} Error result or null if valid
*/
function validateNinoLetters(prefix, suffix, errorResult) {
const invalidLetters = ['D', 'F', 'I', 'Q', 'U', 'V'];
if (invalidLetters.includes(prefix[0]))
return errorResult('INVALID_FIRST_LETTER', { letter: prefix[0] });
if (invalidLetters.includes(prefix[1]))
return errorResult('INVALID_SECOND_LETTER', { letter: prefix[1] });
if (suffix && INVALID_SUFFIXES.includes(suffix))
return errorResult('INVALID_SUFFIX', { suffix });
return null;
}
/**
* Validates NINO prefix and number patterns according to HMRC rules
* @param {string} prefix - Two-letter prefix
* @param {string} numbers - Six-digit number sequence
* @param {Function} errorResult - Error result factory function
* @returns {Object|null} Error result or null if valid
*/
function validateNinoPatterns(prefix, numbers, errorResult) {
if (INVALID_PREFIXES.includes(prefix))
return errorResult('INVALID_PREFIX', { prefix });
if (/^(\d)\1{5}$/.test(numbers))
return errorResult('INVALID_NUMBER_PATTERN', { numbers });
return null;
}
/**
* Validates a UK National Insurance Number with detailed error reporting.
*
* This function provides comprehensive validation with detailed error messages
* and suggestions for fixing common issues. It handles all edge cases and
* provides both human-readable messages and machine-readable error codes.
*
* @param {string} nino - The NINO to validate
* @param {ValidationOptions} [options={}] - Validation options
* @param {boolean} [options.allowSpaces=true] - Allow spaces in the NINO
* @param {boolean} [options.requireSuffix=false] - Require the suffix letter
*
* @returns {ValidationResult} Object containing validation result and detailed error information
*
* @example
* // Valid NINO
* validateNINOWithDetails('AB123456C');
* // Returns: { isValid: true, error: null, errorCode: null, suggestion: null }
*
* @example
* // Invalid length (too short)
* validateNINOWithDetails('ABC123');
* // Returns: {
* // isValid: false,
* // error: 'NINO too short (6 characters). Minimum 8 characters required',
* // errorCode: 'TOO_SHORT',
* // suggestion: 'Ensure the NINO has 2 letters, 6 digits, and optionally 1 letter'
* // }
*
* @example
* // Invalid prefix
* validateNINOWithDetails('BG123456C');
* // Returns: {
* // isValid: false,
* // error: 'Invalid prefix "BG". This prefix is not used by HMRC',
* // errorCode: 'INVALID_PREFIX',
* // suggestion: 'Use a valid prefix like AB, CD, EF, etc.'
* // }
*
* @since 1.0.0
*/
function validateNINOWithDetails(nino, options = {}) {
const { allowSpaces = true, requireSuffix = false } = options;
// Helper for error return
const errorResult = (errorCode, params = {}) => {
const message = getLocalizedMessage(errorCode, params);
return {
isValid: false,
error: message.error,
errorCode,
suggestion: message.suggestion,
};
};
// Step 1: Basic input validation
const basicError = validateBasicInput(nino, errorResult);
if (basicError) return basicError;
// Step 2: Clean and normalize
const cleanResult = cleanAndNormalizeNino(nino, allowSpaces, errorResult);
if (typeof cleanResult !== 'string') return cleanResult; // Error occurred
const cleanNino = cleanResult;
// Step 3: Length validation
const lengthError = validateNinoLength(cleanNino, errorResult);
if (lengthError) return lengthError;
// Step 4: Format validation
const ninoRegex = requireSuffix
? /^[A-Z]{2}\d{6}[A-Z]$/
: /^[A-Z]{2}\d{6}[A-Z]?$/;
if (!ninoRegex.test(cleanNino)) {
return getFormatError(cleanNino, requireSuffix, errorResult);
}
// Step 5: Extract components
const prefix = cleanNino.substring(0, 2);
const numbers = cleanNino.substring(2, 8);
const suffix = cleanNino.length === 9 ? cleanNino[8] : '';
// Step 6: Letter validation
const letterError = validateNinoLetters(prefix, suffix, errorResult);
if (letterError) return letterError;
// Step 7: Pattern validation
const patternError = validateNinoPatterns(prefix, numbers, errorResult);
if (patternError) return patternError;
// All validations passed
return {
isValid: true,
error: null,
errorCode: null,
suggestion: null,
};
}
// Helper for format errors to reduce complexity in main function
function getFormatError(cleanNino, requireSuffix, errorResult) {
if (!/^[A-Z]{2}/.test(cleanNino)) return errorResult('INVALID_PREFIX_FORMAT');
if (!/^\d{6}$/.test(cleanNino.substring(2, 8)))
return errorResult('INVALID_NUMBER_FORMAT');
if (requireSuffix && cleanNino.length === 8)
return errorResult('MISSING_REQUIRED_SUFFIX');
if (cleanNino.length === 9 && !/^[A-Z]$/.test(cleanNino[8]))
return errorResult('INVALID_SUFFIX_FORMAT');
return errorResult('INVALID_FORMAT');
}
/**
* Formats a NINO string with standard UK government spacing.
*
* The standard format is: XX ## ## ## X (with spaces between number groups).
* Only valid NINOs will be formatted; invalid inputs return null.
*
* @param {string} nino - The NINO to format
*
* @returns {string|null} The formatted NINO string, or null if invalid
*
* @example
* formatNINO('AB123456C'); // 'AB 12 34 56 C'
* formatNINO('ab123456c'); // 'AB 12 34 56 C' (normalized)
* formatNINO('AB123456'); // 'AB 12 34 56' (no suffix)
* formatNINO(' AB123456C '); // 'AB 12 34 56 C' (trimmed)
* formatNINO('invalid'); // null
*
* @since 1.0.0
*/
function formatNINO(nino) {
// Only format if valid
if (!validateNINO(nino)) {
return null;
}
// Clean and normalize the input
const cleanNino = nino.toUpperCase().replace(/\s/g, '');
// Extract components for formatting
const prefix = cleanNino.substring(0, 2);
const part1 = cleanNino.substring(2, 4);
const part2 = cleanNino.substring(4, 6);
const part3 = cleanNino.substring(6, 8);
const suffix = cleanNino.substring(8, 9);
// Format with spaces and trim any trailing space
return `${prefix} ${part1} ${part2} ${part3} ${suffix}`.trim();
}
/**
* @typedef {Object} ParsedNINO
* @property {string} prefix - Two-letter prefix (e.g., 'AB')
* @property {string} numbers - Six-digit number sequence (e.g., '123456')
* @property {string|null} suffix - Single suffix letter or null if not present
* @property {string} formatted - Standardized formatted version
* @property {string} original - Original input string
*/
/**
* Extracts and validates components from a NINO string.
*
* Parses a NINO into its constituent parts and provides both the
* original input and standardized formatted version. Only valid
* NINOs will be parsed; invalid inputs return null.
*
* @param {string} nino - The NINO to parse
*
* @returns {ParsedNINO|null} Object containing NINO components, or null if invalid
*
* @example
* parseNINO('AB123456C');
* // Returns: {
* // prefix: 'AB',
* // numbers: '123456',
* // suffix: 'C',
* // formatted: 'AB 12 34 56 C',
* // original: 'AB123456C'
* // }
*
* @example
* parseNINO('AB123456');
* // Returns: {
* // prefix: 'AB',
* // numbers: '123456',
* // suffix: null,
* // formatted: 'AB 12 34 56',
* // original: 'AB123456'
* // }
*
* @example
* parseNINO('invalid'); // null
*
* @since 1.0.0
*/
function parseNINO(nino) {
// Only parse if valid
if (!validateNINO(nino)) {
return null;
}
// Clean and normalize
const cleanNino = nino.toUpperCase().replace(/\s/g, '');
return {
prefix: cleanNino.substring(0, 2),
numbers: cleanNino.substring(2, 8),
suffix: cleanNino.substring(8, 9) || null,
formatted: formatNINO(nino),
original: nino,
};
}
/**
* Generates a random valid NINO for testing purposes.
*
* Creates a cryptographically random NINO that passes all validation rules.
* This function includes safeguards against infinite loops and will fallback
* to known valid values if random generation fails.
*
* Note: This is intended for testing and development only. Do not use
* generated NINOs for any official purposes.
*
* @returns {string} A randomly generated valid NINO
*
* @example
* const testNINO = generateRandomNINO();
* console.log(testNINO); // e.g., 'JK789012M'
* console.log(validateNINO(testNINO)); // always true
*
* @example
* // Generate test data
* const testCases = Array.from({ length: 10 }, () => generateRandomNINO());
*
* @since 1.0.0
*/
function generateRandomNINO() {
// Valid first letters (excluding D, F, I, Q, U, V and letters that make all combinations invalid)
const validFirstLetters = 'ABCEJKLMPRSTWXYZ'; // Removed G, N, O as they make all combinations invalid
// Valid second letters (excluding D, F, I, Q, U, V)
const validSecondLetters = 'ABCEGJKLMNOPRSTWXYZ';
// Valid suffix letters
const validSuffixes = 'ABCEGJKLMNOPRSTWXYZ';
const firstLetter =
validFirstLetters[Math.floor(Math.random() * validFirstLetters.length)];
let secondLetter =
validSecondLetters[Math.floor(Math.random() * validSecondLetters.length)];
// Ensure we don't create an invalid prefix combination (with safety counter)
let prefix = firstLetter + secondLetter;
let attempts = 0;
const maxAttempts = 100;
while (INVALID_PREFIXES.includes(prefix) && attempts < maxAttempts) {
secondLetter =
validSecondLetters[Math.floor(Math.random() * validSecondLetters.length)];
prefix = firstLetter + secondLetter;
attempts++;
}
// Fallback to a known valid prefix if we couldn't find one
if (INVALID_PREFIXES.includes(prefix)) {
prefix = 'AB'; // Known valid prefix
}
// Generate 6 random digits (ensure they're not all the same) with safety counter
let numbers;
let numberAttempts = 0;
const maxNumberAttempts = 1000;
do {
numbers = Math.floor(Math.random() * 1000000)
.toString()
.padStart(6, '0');
numberAttempts++;
} while (/^(\d)\1{5}$/.test(numbers) && numberAttempts < maxNumberAttempts);
// Fallback to a known valid number if we couldn't generate one
if (/^(\d)\1{5}$/.test(numbers)) {
numbers = '123456'; // Known valid number pattern
}
const suffix =
validSuffixes[Math.floor(Math.random() * validSuffixes.length)];
return prefix + numbers + suffix;
}
// Import and re-export i18n functions
const i18n = require('./src/i18n');
module.exports = {
validateNINO,
formatNINO,
parseNINO,
generateRandomNINO,
validateNINOWithDetails,
// Internationalization functions
setLanguage: i18n.setLanguage,
getCurrentLanguage: i18n.getCurrentLanguage,
getSupportedLanguages: i18n.getSupportedLanguages,
isLanguageSupported: i18n.isLanguageSupported,
detectLanguage: i18n.detectLanguage,
initializeI18n: i18n.initializeI18n,
};