Validation d’un IBAN en C#
26 09 2007
J’ai passé trop de temps à chercher sur Internet comment réaliser la validation d’un code IBAN en C#.
Ce bout de code valide donc que le n° IBAN saisi est correct. Attention il ne valide pas en fonction du pays mais calcule seulement la clé « checksum ».
Ce n’est pas du grand art mais cela permettra à d’autres d’éviter de passer une heure à chercher !
Et si vous êtes plutôt VB.NET, pas de problème, http://www.codechanger.com/ est là…
private static bool ValidateIBAN(string ibanValue)
{
string iban = ibanValue.Substring(4, ibanValue.Length - 4)
+ ibanValue.Substring(0, 4);
StringBuilder sb = new StringBuilder();
foreach (char c in iban)
{
int v;
if (Char.IsLetter(c))
{
v = c - 'A' + 10;
}
else
{
v = c - '0';
}
sb.Append(v);
}
string checkSumString = sb.ToString();
int checksum = int.Parse(checkSumString.Substring(0, 1));
for (int i = 1; i < checkSumString.Length; i++)
{
int v = int.Parse(checkSumString.Substring(i, 1));
checksum *= 10;
checksum += v;
checksum %= 97;
}
return checksum == 1;
}
Moi j’aurais pu te dire commencer valider une clef RIB en PL/SQL comme je l’ai fais y a pas longtemps… Mais c’est moins sexy 😉
Hi, thank you very much for your code, has saved my life from implementing a validation function from scratch… ^_^
I reformatted a bit your code to improve readability removing some variables and replaced the for cycle with another foreach.
If the code below becomes messed up, I’ve uploaded the snippet here: pastebin.com.
public static bool ValidateIban(String Iban){
StringBuilder sbCheck;
Int32 intValue;
Int32 intChecksum;
Iban = Iban.Substring(4, Iban.Length - 4) + Iban.Substring(0, 4);
sbCheck = new StringBuilder();
foreach (Char cCharacter in Iban)
{
intValue = (Char.IsLetter(cCharacter)) ? (cCharacter - 'A' + 10) : (cCharacter - '0');
sbCheck.Append(intValue);
}
intChecksum = Int32.Parse(sbCheck.ToString(0, 1));
foreach (Char cCharacter in sbCheck.ToString(1, sbCheck.Length - 1))
{
intValue = Int32.Parse(cCharacter.ToString());
intChecksum *= 10;
intChecksum += intValue;
intChecksum %= 97;
}
return (intChecksum == 1);
}