Validate IBAN Checksums Before Storage
Normalize and validate IBAN values with length, character, and mod-97 checksum rules before persisting account data.
Code
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()
How it works
Validate IBAN Checksums Before Storage reduces to the functions normalize_iban, iban_checksum, validate_iban and main.
Iteration happens inside for value, expected in samples.items() — everything outside it runs once. annotations are the only symbols borrowed from __future__ — the coupling is explicit and narrow.
What to watch for
- Plan for an install step:
__future__is a real dependency, resolved by the package manager.
Applying it
The main signature reads def normalize_iban(value: str) -> str
main sequences validate_iban and normalize_iban; executing the file runs that flow once.
Statements that matter
def normalize_iban(value: str) -> str:
return re.sub(r"\s+", "", value).upper()
def validate_iban(value: str) -> bool:
iban = normalize_iban(value)
if not IBAN_RE.match(iban):
return False
return iban_checksum(iban) == 1
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
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.IBAN ValidatorValidate International Bank Account Numbers with structure checks, per-country length rules, and the ISO 13616 mod-97 checksum.ISBN ValidatorValidate ISBN-10 and ISBN-13 identifiers with checksum verification, hyphen-tolerant input, and conversion between the two forms.Luhn Checksum ValidatorValidate numeric identifiers with the Luhn algorithm and see the checksum sum and suggested final digit on failure.
FAQ
- Are there third-party dependencies?
- `__future__` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.