Posted by admin Tue, 20 Mar 2007 05:00:00 GMT

Recently, while working on one of our client’s projects, I found myself needing to validate credit card numbers. Of course the most secure way to do it is to use your merchant services (i.e., Verisign PayFlowPro, etc.). However most often those services cost anywhere from $15/month and 3 cents per transaction and up.

For most purposes the business wants to simply prevent its customers from fat-fingering their credit card numbers when typing it in. But there are several pieces of information that can be validated for any given credit card like: expiration date, billing address, security code, cardholder’s name, etc.

For our purposes we simply wanted to protect customers from their own fat fingers. The Luhn algorithm does nicely for that purpose, and for the most part, keeps honest people honest.

Here it is using Ruby:

def validate_credit_card(number)
  reverse_card_num = number.reverse
  sum = 0
  reverse_card_num.scan(/./).each_with_index do |digit, index|
    digit = digit.to_i
    digit *= 2 if index % 2 != 0
    if digit.to_s.length == 2
      first_num = digit.to_s[0..0]
      second_num = digit.to_s[1..1]
      digit = first_num.to_i + second_num.to_i
    end
    sum += digit
  end
  pass = sum % 10 == 0 ? true : false
end

To use it just pass in your 15-16 digit credit card number and it will return a boolean for pass or fail.

When I have some more time I’ll post some additional validation code that CBCI currently uses for credit cards.