-4

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

punund
  • 4,321
  • 3
  • 34
  • 45
  • 2
    Just google `npm iban validate`, you will find several packages that do this for you. On page 1 I already got `iban`, `ibantools`, `ibankit`, `iban-number-validation` and `fast-iban` to choose from. If you don't want to use a package for that, you can also look at the source code of them to get inspiration of how to do it. – CherryDT Jun 20 '22 at 15:02
  • Thank you very much, but I need to get mod 97-10 of this iban to have two digit validation code – Pedro Marques Jun 20 '22 at 15:05
  • 1
    Do you want to do this in Javascript or sql? Why did you tag both? – HoneyBadger Jun 20 '22 at 15:24
  • I want both ways if you have – Pedro Marques Jun 20 '22 at 15:26

1 Answers1

1

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'));
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132