Groovy web console

subscribe to the feed Subscribe
to this
site

IBAN validator

Published 2 weeks ago by JMR with tags IBAN
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def isValidIBAN = { String accountNumber ->
    if (accountNumber == null) return false;
    accountNumber = accountNumber.replaceAll("\\s+","").toUpperCase();

    def fullPattern = java.util.regex.Pattern.compile("([A-Z]{2})([0-9]{2})(\\w{2,30})");
    def matcher = fullPattern.matcher(accountNumber);
    if (!matcher.matches()) return false;
    String numeric = matcher.group(3) + matcher.group(1) + matcher.group(2);

    def sb = new StringBuffer();
    for (int i = 0; i < numeric.length(); i++) {
        char c = numeric.charAt(i);
        if (Character.isDigit(c)) {
            sb.append(Character.digit(c,10));
        } else if (Character.isUpperCase(c)) {
            sb.append(c - 55); //substract from ASCII value so that A=10,B=11,...,Z=35
        } else {
            return false;
        }
    }
    numeric = sb.toString();

    return (new BigDecimal(numeric).remainder(BigDecimal.valueOf(97)).intValue() == 1);
}
['NL37INGB2370432586', 'FI1639428968362836', 'CM2633684216252218954382769', 'qwerty', 'NL36INGB2370432586', 'FI1639428968362837'].each { iban ->
    println "$iban : ${isValidIBAN(iban)}";
}