salix/services/loopback/common/validations/validateDni.js

73 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-03-12 13:13:36 +00:00
module.exports = function(fi, country) {
2018-03-13 11:14:06 +00:00
if (fi == null || country == null)
return true;
if (typeof fi != 'string' || typeof country != 'string')
return false;
2017-11-16 11:02:45 +00:00
2018-03-12 13:13:36 +00:00
fi = fi.toUpperCase();
2018-03-13 11:14:06 +00:00
country = country.toLowerCase();
2017-11-16 11:02:45 +00:00
2018-02-27 09:00:43 +00:00
let len = fi.length;
2017-11-16 11:02:45 +00:00
2018-02-27 09:00:43 +00:00
let validators = {
es: {
regExp: /^[A-Z0-9]\d{7}[A-Z0-9]$/,
2018-02-27 09:00:43 +00:00
validate: () => {
let isCif = /[A-W]/.test(fi.charAt(0));
let lastDigit = fi.charAt(len - 1);
let computedDigit;
2017-11-16 11:02:45 +00:00
2018-02-27 09:00:43 +00:00
if (isCif) {
let numbers = fi.substring(1, 8)
.split('')
.map(x => parseInt(x));
let pairSum = numbers
.filter((_, i) => i % 2 != 0)
.reduce((a, x) => a + x);
let oddSum = numbers
.filter((_, i) => i % 2 == 0)
.map(x => x * 2)
.join('')
.split('')
.map(x => parseInt(x))
.reduce((a, x) => a + x);
let sum = (pairSum + oddSum).toString();
let units = parseInt(sum.charAt(sum.length - 1));
2018-03-12 13:13:36 +00:00
let control = units == 0 ? 0 : 10 - units;
2018-02-27 09:00:43 +00:00
let index = 'JABCDEFGHI'.indexOf(lastDigit);
computedDigit = index == -1 ? control.toString() : index;
} else {
// Foreign NIF
let index = 'XYZ'.indexOf(fi.charAt(0));
let nif = index == -1 ? fi : index.toString() + fi.substring(1);
2017-11-16 11:02:45 +00:00
let rest = parseInt(nif.substring(0, 8)) % 23;
2018-02-27 09:00:43 +00:00
computedDigit = 'TRWAGMYFPDXBNJZSQVHLCKE'.charAt(rest);
}
return computedDigit == lastDigit;
}
},
fr: {
regExp: /^[A-Z0-9]{2}\d{9}$/
2018-02-27 09:00:43 +00:00
},
it: {
regExp: /^\d{11}$/
},
pt: {
regExp: /^\d{9}$/
2017-11-16 11:02:45 +00:00
}
};
2018-02-27 09:00:43 +00:00
let validator = validators[country];
if (!validator)
2018-03-12 16:18:18 +00:00
return true;
2018-02-27 09:00:43 +00:00
return validator.regExp.test(fi)
2018-02-27 09:00:43 +00:00
&& (!validator.validate || validator.validate());
2017-11-16 11:02:45 +00:00
};