gazpacho

Groovy Credit Card Number Validation

Back in March I attended a software conference hosted in St. Louis called No Fluff, Just Stuff. The lectures introduced me to some cool new technology. It was small and intimate. I had an opportunity to speak to the instructors and conference organizer.

The classes I took covered these technologies: Ajax, Hibernate, Spring, Terracotta, Grails, Groovy and GWT

During one of Jeff Brown's Grails talks I heard him say that there is built-in validation of credit card numbers, but it is limited to just checking the size. It is possible to validate the value of the number using the Luhn Algorithm. So, the following is my implementation of Luhn validation written in Groovy and suitable for use in Grails.

class LuhnValidator { def isValidCreditCardNumber(number) { def sum = 0 def alternate = false number.reverse().each { value -> if (value =~ /\d/) { def n = value.toInteger() if (alternate) { n *= 2 if (n > 9) { n = n % 10 + 1 } } sum += n alternate = !alternate } } sum % 10 == 0 } }
spacerPosted at 9:16 PM