calculate and check an IBAN

991 views Asked by At

Algorithm that calculates the IBAN key and compares it with the key entered in iban:

  • Remove the country code and key
  • Put the country code and a key 00 at the end
  • convert characters in number (A=10; B=11; ......)
  • calculate modulo 97
  • remove the result at 98
  • you have the key

The modulo function is rewritten for large numbers

check my answer below as a solution

1

There are 1 answers

4
Estelle On
function IsIbanValid(iban) {
    // example "FR76 1020 7000 2104 0210 1346 925"
    //         "CH10 0023 00A1 0235 0260 1"

    var keyIBAN = iban.substring(2, 4);    // 76
    var compte = iban.substring(4, iban.length );
    var compteNum = '';
    compte = compte + iban.substring(0, 2);

    // convert  characters in numbers
    var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (i = 0; i < compte.length; i++) {
        if (isNaN(compte[i]))
            for (j = 0; j < alphabet.length; j++) {
                if (compte[i] == alphabet[j])
                    compteNum += (j + 10).toString();
            }
        else
            compteNum += compte[i];
    }
    compteNum += '00';   // concat 00 for key  
    // end convert

    var result = modulo(compteNum, 97);

    if ((98-result) == keyIBAN)
        return true;
    else
        return false;
}

/// modulo for big numbers, (modulo % can't be used)
function modulo(divident, divisor) {
    var partLength = 10;

    while (divident.length > partLength) {
        var part = divident.substring(0, partLength);
        divident = (part % divisor) + divident.substring(partLength);
    }

    return divident % divisor;
}