salix/loopback/util/validateTin.js

70 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-03-21 11:57:23 +00:00
module.exports = function(tin, country) {
if (tin == null || country == null)
2018-03-13 11:14:06 +00:00
return true;
2018-03-21 11:57:23 +00:00
if (typeof tin != 'string' || typeof country != 'string')
2018-03-13 11:14:06 +00:00
return false;
2017-11-16 11:02:45 +00:00
2018-03-21 11:57:23 +00:00
tin = tin.toUpperCase();
2018-03-13 11:14:06 +00:00
country = country.toLowerCase();
2017-11-16 11:02:45 +00:00
2018-03-21 11:57:23 +00:00
let len = tin.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: () => {
2018-03-21 11:57:23 +00:00
let isCif = /[A-W]/.test(tin.charAt(0));
let lastDigit = tin.charAt(len - 1);
2018-02-27 09:00:43 +00:00
let computedDigit;
2017-11-16 11:02:45 +00:00
2018-02-27 09:00:43 +00:00
if (isCif) {
2018-03-21 11:57:23 +00:00
let numbers = tin.substring(1, 8)
2018-02-27 09:00:43 +00:00
.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-04-03 14:54:41 +00:00
let isLetter = /^[A-Z]$/.test(lastDigit);
computedDigit = isLetter ? 'JABCDEFGHI'.charAt(control) : control.toString();
2018-02-27 09:00:43 +00:00
} else {
// Foreign NIF
2018-03-21 11:57:23 +00:00
let index = 'XYZ'.indexOf(tin.charAt(0));
let nif = index == -1 ? tin : index.toString() + tin.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;
}
},
it: {
2018-03-21 11:57:23 +00:00
regExp: /^(\d{11}|[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z])$/
},
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
2018-03-21 11:57:23 +00:00
return validator.regExp.test(tin)
2018-02-27 09:00:43 +00:00
&& (!validator.validate || validator.validate());
2017-11-16 11:02:45 +00:00
};