Created
May 4, 2012 08:55
-
-
Save flou/2593416 to your computer and use it in GitHub Desktop.
Validate IBAN
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
function validateIban (iban) { | |
const ibanValidationModulo = 97; | |
// On force les caractères alphabétiques en majuscule | |
iban = iban.toUpperCase(); | |
// on supprime les espaces | |
iban = iban.replace(new RegExp(" ", "g"), ""); | |
// le code iban doit faire plus de 4 caractères | |
if (iban.length < 5) { | |
return false; | |
} | |
// puis on transfert les quatre premiers caractères en fin de chaine. | |
modifiedIban = iban.substring(4, iban.length)+iban.substr(0,4); | |
// On convertit les caractères alphabétiques en valeur numérique | |
numericIbanString = ""; | |
for (var index = 0; index < modifiedIban.length; index ++) { | |
currentChar = modifiedIban.charAt(index); | |
currentCharCode = modifiedIban.charCodeAt(index); | |
// si le caractère est un digit, on le recopie | |
if ((currentCharCode > 47) && (currentCharCode < 58)) { | |
numericIbanString = numericIbanString + currentChar; | |
} | |
// si le caractère est une lettre, on le converti en valeur | |
else if ((currentCharCode > 64) && (currentCharCode < 91)) { | |
value = currentCharCode-65+10; | |
numericIbanString = numericIbanString + value; | |
} | |
// sinon, le code iban est invalide (caractère invalide). | |
else { | |
return false; | |
} | |
} | |
// On a maintenant le code iban converti en un nombre. Un très gros nombre. | |
// Tellement gros que javascript ne peut pas le gérer. | |
// Pour calculer le modulo, il faut donc y aller par étapes : | |
// on découpe le nombre en blocs de 5 chiffres. | |
// Pour chaque bloc, on préfixe avec le modulo du bloc précédent (2 chiffres max, | |
// ce qui nous fait un nombre de 7 chiffres max, gérable par javascript). | |
var previousModulo = 0; | |
for (var index = 0; index < numericIbanString.length; index += 5) { | |
subpart = previousModulo+""+numericIbanString.substr(index, 5); | |
previousModulo = subpart % ibanValidationModulo; | |
} | |
return previousModulo == 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment