forked from validatorjs/validator.js
/
isIdentityCard.js
53 lines (44 loc) · 1.34 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
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]);
},
};
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}'`);
}