Module (97%)
Section (71%)

Now, let's add a new exception class and wrap the previous IBAN validating snippet into a function, reformulate the last condition, and use it as a helper function.

To sum up, our validateIBAN(iban) function:

  • requires a parameter; it is a string to check whether it contains an IBAN-compliant account number;
  • raises an IBANValidationError exception when the supplied string carries an incorrectly formulated account number;
  • returns a True value when the account number conforms to all IBAN requirements.

Finally, let's add a loop to check three example IBANs. Pay attention to the fact that the first IBAN value has been modified to raise an exception.

Status of "GB72 HBZU 7006 7212 1253 01" validation: IBAN entered is invalid. Status of "FR76 30003 03620 00020216907 50" validation: correct Status of "DE02100100100152517108" validation: correct

output


Code

class IBANValidationError(Exception):
pass


def validateIBAN(iban):
iban = iban.replace(' ', '')

if not iban.isalnum():
raise IBANValidationError("You have entered invalid characters.")

elif len(iban) < 15:
raise IBANValidationError("IBAN entered is too short.")

elif len(iban) > 31:
raise IBANValidationError("IBAN entered is too long.")

else:
iban = (iban[4:] + iban[0:4]).upper()
iban2 = ''
for ch in iban:
if ch.isdigit():
iban2 += ch
else:
iban2 += str(10 + ord(ch) - ord('A'))
ibann = int(iban2)

if ibann % 97 != 1:
raise IBANValidationError("IBAN entered is invalid.")

return True


test_keys = ['GB72 HBZU 7006 7212 1253 01', 'FR76 30003 03620 00020216907 50', 'DE02100100100152517108' ]

for key in test_keys:
try:
print('Status of "{}" validation: '.format(key))
validateIBAN(key)
except IBANValidationError as e:
print("\t{}".format(e))
else:
print("\tcorrect")
{{ dockerServerErrorMsg }} ×
{{ errorMsg }} ×
{{ successMsg }} ×