Created
April 16, 2013 09:30
-
-
Save DonDebonair/5394643 to your computer and use it in GitHub Desktop.
Basic IBAN check in JAVA following the rules as laid out on (http://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_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
import java.math.BigInteger; | |
public final class IbanTest { | |
public static final int IBANNUMBER_MIN_SIZE = 15; | |
public static final int IBANNUMBER_MAX_SIZE = 34; | |
public static final BigInteger IBANNUMBER_MAGIC_NUMBER = new BigInteger("97"); | |
public static boolean ibanTest(String accountNumber) { | |
String newAccountNumber = accountNumber.trim(); | |
// Check that the total IBAN length is correct as per the country. If not, the IBAN is invalid. We could also check | |
// for specific length according to country, but for now we won't | |
if (newAccountNumber.length() < IBANNUMBER_MIN_SIZE || newAccountNumber.length() > IBANNUMBER_MAX_SIZE) { | |
return false; | |
} | |
// Move the four initial characters to the end of the string. | |
newAccountNumber = newAccountNumber.substring(4) + newAccountNumber.substring(0, 4); | |
// Replace each letter in the string with two digits, thereby expanding the string, where A = 10, B = 11, ..., Z = 35. | |
StringBuilder numericAccountNumber = new StringBuilder(); | |
for (int i = 0;i < newAccountNumber.length();i++) { | |
numericAccountNumber.append(Character.getNumericValue(newAccountNumber.charAt(i))); | |
} | |
// Interpret the string as a decimal integer and compute the remainder of that number on division by 97. | |
BigInteger ibanNumber = new BigInteger(numericAccountNumber.toString()); | |
return ibanNumber.mod(IBANNUMBER_MAGIC_NUMBER).intValue() == 1; | |
} | |
} |
Using regex can be sensible faster.
Moreover using a bit of binary math can avoid using BigInteger.
// Replace each letter in the string with two digits, thereby expanding the string, where A=10, B=11, ..., Z=35.
string modifiedIban = iban.Substring(4) + iban.Substring(0, 4);
modifiedIban = Regex.Replace(modifiedIban, @"\D", m => ((int)m.Value[0] - 55).ToString());
int remainer = 0;
while (modifiedIban.Length >= 7) {
remainer = int.Parse(remainer + modifiedIban.Substring(0, 7)) % 97;
modifiedIban = modifiedIban.Substring(7);
}
remainer = int.Parse(remainer + modifiedIban) % 97;
return (remainer == 1);
I hope it helps
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @dandydev
From the documentation
Character.getNumericValue()
:In case of a negative value returned by this method the BigInteger initialisation will crash. Here is my quick fix: