Skip to content

Instantly share code, notes, and snippets.

@florentx
Last active August 29, 2015 14:17
Show Gist options
  • Save florentx/404d8fe2bd94a9189b7a to your computer and use it in GitHub Desktop.
Save florentx/404d8fe2bd94a9189b7a to your computer and use it in GitHub Desktop.
Validate IBAN or Post Account
POST_TABLE = (0, 9, 4, 6, 8, 2, 7, 1, 3, 5)
IBAN_TABLE = dict([(c, str(idx))
for (idx, c) in enumerate('0123456789abcdefgh'
'ijklmnopqrstuvwxyz')])
def validate_postaccount(value):
"""Check the Post Account."""
if not value:
raise ValueError('Post Account cannot be empty')
# The format is a-b-c
# in b, leading 0s may be stripped
(a, b, c) = value.strip().split('-', 2)
if (not (a + b + c).isdigit()) or len(a) != 2 or len(b) > 6 or len(c) != 1:
raise ValueError('Post Account - invalid format')
(a, b, checksum) = (int(a), int(b), int(c))
key = 0
for char in "%02d%06d" % (a, b):
key = POST_TABLE[(key + int(char)) % 10]
if checksum != -key % 10:
raise ValueError('Post Account - invalid checksum')
return "%02d-%06d-%d" % (a, b, checksum)
def validate_iban(value):
"""Check the IBAN number."""
if not value:
raise ValueError('IBAN number cannot be empty')
# keep only alphanumeric chars and convert to lower case.
iban = ''.join([c for c in value if c.isalnum()]).lower()
# the first four digits are shifted to the end
checkval = iban[4:] + iban[:4]
# letters are transformed into numbers (a = 10, b = 11, ...)
checkval = ''.join([IBAN_TABLE[c] for c in checkval])
# iban is correct if modulo 97 == 1
if int(checkval) % 97 != 1:
raise ValueError('IBAN number is invalid')
return iban
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment