首页 > 解决方案 > 计算并检查 IBAN

问题描述

计算 IBAN 密钥并将其与在 iban 中输入的密钥进行比较的算法:

为大数重写模函数

在下面检查我的答案作为解决方案

标签: javascriptiban

解决方案


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;
}

推荐阅读