Validating credit card numbers in code using the Lunh algorithm

I’ve been writing billing system code for years, but this is something I’ve not known until today: VISA, MasterCard and American Express credit card numbers can be checked for validity (meaning you gain one extra check against someone typing in random numbers) using what’s known as the Luhn algorithm.

Credit Card Validation – Check Digits

The following steps are required to validate the primary account number:

Step 1: Double the value of alternate digits of the primary account number beginning with the second digit from the right (the first right-hand digit is the check digit.)

Step 2: Add the individual digits comprising the products obtained in Step 1 to each of the unaffected digits in the original number.

Step 3: The total obtained in Step 2 must be a number ending in zero (30, 40, 50, etc.) for the account number to be validated.

For example, to validate the primary account number 49927398716:

Step 1:

        4 9 9 2 7 3 9 8 7 1 6
         x2  x2  x2  x2  x2 
         18   4   6  16   2

Step 2: 4 +(1+8)+ 9 + (4) + 7 + (6) + 9 +(1+6) + 7 + (2) + 6

Step 3: Sum = 70 : Card number is validated

Note: Card is valid because the 70/10 yields no remainder.

In a world of Ruby gems and PHP classes it’s become less likely that a developer will need to perform their own credit card number validations, but it’s still an interesting little bit of trivia.¬†You can find more here regarding the simplified transaction and currency exchange services.

Leave a Reply

Your email address will not be published. Required fields are marked *