/
isIdentityCard.js
122 lines (103 loc) · 2.69 KB
/
isIdentityCard.js
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
import assertString from './util/assertString';
const validators = {
ES: (str) => {
assertString(str);
const DNI = /^[0-9X-Z][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/;
const charsValue = {
X: 0,
Y: 1,
Z: 2,
};
const controlDigits = [
'T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B',
'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E',
];
// sanitize user input
const sanitized = str.trim().toUpperCase();
// validate the data structure
if (!DNI.test(sanitized)) {
return false;
}
// validate the control digit
const number = sanitized.slice(0, -1).replace(/[X,Y,Z]/g, char => charsValue[char]);
return sanitized.endsWith(controlDigits[number % 23]);
},
'he-IL': (str) => {
const DNI = /^\d{9}$/;
// sanitize user input
const sanitized = str.trim();
// validate the data structure
if (!DNI.test(sanitized)) {
return false;
}
const id = sanitized;
let sum = 0,
incNum;
for (let i = 0; i < id.length; i++) {
incNum = Number(id[i]) * ((i % 2) + 1); // Multiply number by 1 or 2
sum += incNum > 9 ? incNum - 9 : incNum; // Sum the digits up and add to total
}
return sum % 10 === 0;
},
'zh-TW': (str) => {
const ALPHABET_CODES = {
A: 10,
B: 11,
C: 12,
D: 13,
E: 14,
F: 15,
G: 16,
H: 17,
I: 34,
J: 18,
K: 19,
L: 20,
M: 21,
N: 22,
O: 35,
P: 23,
Q: 24,
R: 25,
S: 26,
T: 27,
U: 28,
V: 29,
W: 32,
X: 30,
Y: 31,
Z: 33,
};
const sanitized = str.trim().toUpperCase();
if (!/^[A-Z][0-9]{9}$/.test(sanitized)) return false;
return Array.from(sanitized).reduce((sum, number, index) => {
if (index === 0) {
const code = ALPHABET_CODES[number];
return ((code % 10) * 9) + Math.floor(code / 10);
}
if (index === 9) {
return ((10 - (sum % 10)) - Number(number)) % 10 === 0;
}
return sum + (Number(number) * (9 - index));
}, 0);
},
};
export default function isIdentityCard(str, locale) {
assertString(str);
if (locale in validators) {
return validators[locale](str);
} else if (locale === 'any') {
for (const key in validators) {
// https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes
// istanbul ignore else
if (validators.hasOwnProperty(key)) {
const validator = validators[key];
if (validator(str)) {
return true;
}
}
}
return false;
}
throw new Error(`Invalid locale '${locale}'`);
}