Credit card type and luhn check in ruby

I was looking at implementing a luhn and credit card type check the other day in java and I noticed that there seems to be a lack of code for doing this in ruby. So I figured I would put something together for doing the checks in ruby.

The following function will do a luhn check for a given number (any number not just credit card numbers). The luhn algorithm is fairly simple, if you want to learn more about it check here.

  def luhnCheck(ccNumber)
  ccNumber = ccNumber.gsub(/D/, '')
  cardLength = ccNumber.length
  parity = cardLength % 2

  sum = 0
  for i in 0...cardLength
    digit = ccNumber[i] - 48

    if i % 2 == parity
      digit = digit * 2

    if digit > 9
      digit = digit - 9

    sum = sum + digit

  return (sum % 10) == 0

Before running the luhn check you may want to verify that you have a valid card type or at least one you want to accept. The following function will do that based on the current bin ranges for the differenct companies as of today (for more on this see the following: credit card number information and BIN range information). N.B. Bin ranges change from time to time so this will become dated. It should be easy enough to find the updated ranges.

  def ccTypeCheck(ccNumber)
  ccNumber = ccNumber.gsub(/D/, '')
  case ccNumber
    when /^3[47]d{13}$/ then return "AMEX"
    when /^4d{12}(d{3})?$/ then return "VISA"
    when /^5d{15}|36d{14}$/ then return "MC"
    when /^6011d{12}|650d{13}$/ then return "DISC"
    when /^3(0[0-5]|8[0-1])d{11}$/ then return "DINERS"
    when /^(39d{12})|(389d{11})$/ then return "CB"
    when /^3d{15}|1800d{11}|2131d{11}$/ then return "JCB"
    else return "NA"

Tags: ,

Leave a Reply

Your email address will not be published.