Last active
March 18, 2019 08:00
-
-
Save francescozanoni/4e8fcd563b1ac1a3607146e0c2f913a2 to your computer and use it in GitHub Desktop.
[JS] IBAN check digits calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Calculate IBAN check digits. | |
* | |
* Inspired by https://github.com/arhs/iban.js/blob/master/iban.js | |
* | |
* @param string countryCode ISO 3166 2-letter country code, e.g. "FR" | |
* @param string bban IBAN without country code and without check digits, e.g. "20041010050500013M02606" | |
* | |
* @return string e.g. "14" | |
*/ | |
function calculateCheckDigits(countryCode, bban) { | |
// Fake IBAN: IBAN with fake check digits, on which real check digits are calculated | |
var fakeIban = countryCode + '00' + bban; | |
// Standardize fake IBAN, according to ISO 13616 | |
fakeIban = function (iban) { | |
iban = iban.toUpperCase(); | |
iban = iban.substr(4) + iban.substr(0,4); | |
return iban | |
.split('') | |
.map(function(n) { | |
var code = n.charCodeAt(0); | |
if (code >= 'A'.charCodeAt(0) && code <= 'Z'.charCodeAt(0)){ | |
// A = 10, B = 11, ... Z = 35 | |
return code - 'A'.charCodeAt(0) + 10; | |
} else { | |
return n; | |
} | |
}).join(''); | |
}(fakeIban); | |
// Calculate check digits | |
var checkDigits = function (iban) { | |
var remainder = iban; | |
var block; | |
while (remainder.length > 2){ | |
block = remainder.slice(0, 9); | |
remainder = parseInt(block, 10) % 97 + remainder.slice(block.length); | |
} | |
return parseInt(remainder, 10) % 97; | |
}(fakeIban); | |
// Format check digits | |
var checkDigitsAsAtring = ('0' + (98 - checkDigits)).slice(-2); | |
return checkDigitsAsAtring; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment