Validate IBAN Checksums Before Storage

Normalize and validate IBAN values with length, character, and mod-97 checksum rules before persisting account data.

PythonForm Validation

Code

snippet
from __future__ import annotations

import re

IBAN_RE = re.compile(r"^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$")


def normalize_iban(value: str) -> str:
    return re.sub(r"\s+", "", value).upper()


def iban_checksum(iban: str) -> int:
    rearranged = iban[4:] + iban[:4]
    digits = "".join(str(int(char, 36)) for char in rearranged)
    return int(digits) % 97


def validate_iban(value: str) -> bool:
    iban = normalize_iban(value)
    if not IBAN_RE.match(iban):
        return False
    return iban_checksum(iban) == 1


def main() -> None:
    samples = {
        "GB82 WEST 1234 5698 7654 32": True,
        "DE89 3704 0044 0532 0130 00": True,
        "GB82 WEST 1234 5698 7654 33": False,
    }
    for value, expected in samples.items():
        result = validate_iban(value)
        print(f"{normalize_iban(value)} -> {result}")
        assert result is expected


if __name__ == "__main__":
    main()