How to get a string of an IBAN number. I need to calculate the check digit, but there are too many characters.
This is an example IBAN: BR0012345678901234567890123
How to get a string of an IBAN number. I need to calculate the check digit, but there are too many characters.
This is an example IBAN: BR0012345678901234567890123
IBAN validation is described on the Wikipedia page under "Validating the IBAN". Just follow the algorithm as described.
Follow the code below to see how validation happens step-by-step.
Note: BigInt is required to calculate the modulo.
const validate = (iban) => {
const
[, head, tail] = iban.split(/(^\w{4})(\w+)$/),
rearrange = `${tail}${head}`,
replace = rearrange
.split('')
.map(c =>
/[a-z]/i.test(c)
? c.toLowerCase().charCodeAt(0) - 87
: parseInt(c, 10)
)
.join('')
return BigInt(replace) % 97n === 1n;
};
// This IBAN is invalid, since the remainder is not 1
console.log(validate('BR0012345678901234567890123'));
// Valid, via https://www.iban.com/iban-checker example
console.log(validate('GB33BUKB20201555555555'));
This can be shortened to simply:
const validate = (iban) =>
BigInt([...iban.slice(4), ...iban.slice(0, 4)]
.map(c => /[a-z]/i.test(c) ? c.toLowerCase().charCodeAt(0) - 87 : c)
.join('')) % 97n === 1n;
// This IBAN is invalid, since the remainder is not 1
console.log(validate('BR0012345678901234567890123'));
// Valid, via https://www.iban.com/iban-checker example
console.log(validate('GB33BUKB20201555555555'));