java 43 lines · 8 steps

Validating IBANs with the mod-97 checksum

A stateless validator that checks IBAN structure, country length, and the ISO 7064 mod-97 checksum.

Explained by highlit
1public final class IbanValidator {
2 
3 private static final Map<String, Integer> COUNTRY_LENGTHS = Map.ofEntries(
4 Map.entry("DE", 22), Map.entry("FR", 27), Map.entry("GB", 22),
5 Map.entry("NL", 18), Map.entry("ES", 24), Map.entry("IT", 27),
6 Map.entry("BE", 16), Map.entry("CH", 21), Map.entry("AT", 20)
7 );
8 
9 private IbanValidator() {
10 }
11 
12 public static boolean isValid(String iban) {
13 if (iban == null) {
14 return false;
15 }
16 
17 String normalized = iban.replace(" ", "").toUpperCase();
18 if (!normalized.matches("[A-Z]{2}\\d{2}[A-Z0-9]+")) {
19 return false;
20 }
21 
22 String country = normalized.substring(0, 2);
23 Integer expectedLength = COUNTRY_LENGTHS.get(country);
24 if (expectedLength == null || normalized.length() != expectedLength) {
25 return false;
26 }
27 
28 String rearranged = normalized.substring(4) + normalized.substring(0, 4);
29 return computeMod97(rearranged) == 1;
30 }
31 
32 private static int computeMod97(String rearranged) {
33 int remainder = 0;
34 for (int i = 0; i < rearranged.length(); i++) {
35 char c = rearranged.charAt(i);
36 int value = Character.isLetter(c) ? c - 'A' + 10 : c - '0';
37 remainder = value > 9
38 ? (remainder * 100 + value) % 97
39 : (remainder * 10 + value) % 97;
40 }
41 return remainder;
42 }
43}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Layering cheap structural checks before expensive computation lets you reject bad input fast.
  2. 2The mod-97 algorithm avoids huge integers by folding the remainder digit-by-digit as it scans.
  3. 3A private constructor plus static methods signals a pure, stateless utility class.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Validating IBANs with the mod-97 checksum — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code