salix/loopback/util/validateIban.js

52 lines
1.5 KiB
JavaScript
Raw Permalink Normal View History

module.exports = function(iban, countryCode) {
2017-09-25 15:40:02 +00:00
if (iban == null) return true;
if (typeof iban != 'string') return false;
if (countryCode?.toLowerCase() != 'es') return true;
2017-09-25 15:40:02 +00:00
iban = iban.toUpperCase();
iban = trim(iban);
2018-03-13 11:14:06 +00:00
iban = iban.replace(/\s/g, '');
2017-09-25 15:40:02 +00:00
if (iban.length != 24)
2017-10-13 14:23:00 +00:00
return false;
2017-09-25 15:40:02 +00:00
// Se coge las primeras dos letras y se pasan a números
let letter1 = iban.substring(0, 1);
let letter2 = iban.substring(1, 2);
let num1 = getIbanNumber(letter1);
let num2 = getIbanNumber(letter2);
2017-10-13 14:23:00 +00:00
// Se sustituye las letras por números.
let isbanaux = String(num1) + String(num2) + iban.substring(2);
2017-10-13 14:23:00 +00:00
2017-09-25 15:40:02 +00:00
// Se mueve los 6 primeros caracteres al final de la cadena.
2017-10-13 14:23:00 +00:00
isbanaux = isbanaux.substring(6) + isbanaux.substring(0, 6);
2017-09-25 15:40:02 +00:00
2017-10-13 14:23:00 +00:00
// Se calcula el resto, llamando a la función module97, definida más abajo
let resto = module97(isbanaux);
2017-10-13 14:23:00 +00:00
if (resto == 1)
2017-09-25 15:40:02 +00:00
return true;
2017-10-13 14:23:00 +00:00
return false;
2017-09-25 15:40:02 +00:00
function module97(iban) {
let parts = Math.ceil(iban.length / 7);
let remainer = '';
2017-10-13 14:23:00 +00:00
for (let i = 1; i <= parts; i++)
2017-10-13 14:23:00 +00:00
remainer = String(parseFloat(remainer + iban.substr((i - 1) * 7, 7)) % 97);
2017-09-25 15:40:02 +00:00
return remainer;
}
function getIbanNumber(letra) {
let letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2017-09-25 15:40:02 +00:00
return letters.search(letra) + 10;
}
2017-10-13 14:23:00 +00:00
function trim(text) {
2018-03-13 11:14:06 +00:00
return (text || '').replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g, '');
2017-09-25 15:40:02 +00:00
}
2017-10-13 14:23:00 +00:00
};