IBAN Validation and Ruby 1.9

In one of our projects 9flats.com we’re using a short IBAN and SWIFT Validation rule to be sure the user entered valid bank account information.
To know how to validate an IBAN account number, just have a look at this article on wikipedia. Therefore you have to do a few steps to be sure get the right format of an IBAN number:

Validating the IBAN
The basis of the IBAN validation is to convert the IBAN into a number and to perform a basic Mod-97 calculation (as described in ISO 7064) on it. If the IBAN is valid, then the remainder equals 1. Rule process of IBAN validation is:

  • Check that the total IBAN length is correct as per the country. If not, the IBAN is invalid.
  • Move the four initial characters to the end of the string.
  • Replace each letter in the string with two digits, thereby expanding the string, where A=10, B=11, …, Z=35.
  • Interpret the string as a decimal integer and compute the remainder of that number on division by 97.

If the remainder is 1, the checks digits test is passed and the IBAN may be valid.

I found a short (and also funny) blogpost about a validation script in ruby. Unfortunely the expression

iban = value.gsub(/[A-Z]/) { | p | p[0]-55 }

does’n work anymore, because Ruby 1.9 doesn’t return the integer ordinal of a one-character string using p[0]. Instead of that just use the .ord method on a string. So our Ruby 1.9 compatible code will looks like this:

iban = value.gsub(/[A-Z]/) { | p | p.ord-55 }

If you’re using two or more environments (e.g.: Ruby 1.8 and Ruby 1.9) on your production or development machine (I know thats not the way to go, but it could happen for a little time) just ask if Ruby respond to the .ord method.

iban = value.gsub(/[A-Z]/) { |p| (p.respond_to?(:ord) ? p.ord : p[0]) - 55 }

The final code from the blogpost mentioned before will be looks like this:

Small things can be very helpful!