Alireza Noorali
Alireza Noorali

Reputation: 3265

How to check IBAN validation?

How can I validate IBAN (International Bank Account Number) in java to use in Android Apps?

The International Bank Account Number is an internationally agreed system of identifying bank accounts across national borders to facilitate the communication and processing of cross border transactions with a reduced risk of transcription errors.

Upvotes: 2

Views: 7531

Answers (3)

Esat Koç
Esat Koç

Reputation: 224

If you want to use modulo97 == 1 method, you need to first validate check digit is in range of 00-98. Otherwise, you will get valid result checking the iban GB00HLFX11016111455365, but it is not a valid iban (according to the https://www.iban.com/testibans). You simply get into 00 vs 97 overlap as do most programs functioning in production.

There is another strategy for validation. Simply recreate checkdigit and check if it is equal to the one provided.

Upvotes: 0

PotatoesFall
PotatoesFall

Reputation: 355

To implement these steps: https://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN

Also, a long is too small to hold the number. You need a BigInteger.

private boolean isIbanValid(String iban) {
    // remove spaces
    iban = iban.replace("\\s", "");

    // make all uppercase
    iban = iban.toUpperCase();

    // check length - complicated, depends on country. Skipping for now.
    // https://en.wikipedia.org/wiki/International_Bank_Account_Number#Structure

    // move first four letters to the end
    iban = iban.substring(4) + iban.substring(0,4);

    // convert letters to digits
    String total = "";
    for (int i = 0; i < iban.length(); i++) {

        int charValue = Character.getNumericValue(iban.charAt(i));

        if (charValue < 0 || charValue > 35) {
            return false;
        }

        total += charValue;
    }

    // Make BigInteger and check if modulus 97 is 1 
    BigInteger totalInt = new BigInteger(total);
    return totalInt.mod(new BigInteger("97")).equals(BigInteger.ONE);
}

Upvotes: 2

Alireza Noorali
Alireza Noorali

Reputation: 3265

private boolean isIbanValid(String iban) {

    int IBAN_MIN_SIZE = 15;
    int IBAN_MAX_SIZE = 34;
    long IBAN_MAX = 999999999;
    long IBAN_MODULUS = 97;

    String trimmed = iban.trim();

    if (trimmed.length() < IBAN_MIN_SIZE || trimmed.length() > IBAN_MAX_SIZE) {
        return false;
    }

    String reformat = trimmed.substring(4) + trimmed.substring(0, 4);
    long total = 0;

    for (int i = 0; i < reformat.length(); i++) {

        int charValue = Character.getNumericValue(reformat.charAt(i));

        if (charValue < 0 || charValue > 35) {
            return false;
        }

        total = (charValue > 9 ? total * 100 : total * 10) + charValue;

        if (total > IBAN_MAX) {
            total = (total % IBAN_MODULUS);
        }
    }

    return (total % IBAN_MODULUS) == 1;
}

Upvotes: 6

Related Questions