Article | Date posted : 30 January, 2014 | Updated on : 8 March, 2014

Validating credit cards with javascript using Luhn Algorithm

Sponsored Links

Validating credit cards are done using the Luhn Algorithm, this algorithm is a simple check-sum based on multiples of 10’s also known as modulus 10. The algorithm only checks for wrong number combinations. This does not verify if the credit card is real. You can look at it as a pre validation process for when the data is sent to the banking society for real validation. The reason why you would want to use a Luhn algorithm checkup is to avoid accidental errors.

In this article I will explain how we calculate the algorithm and give you both a short and long version of the javascript function that you can use freely in your projects. I have updated this script to be library independent. You can now use it without the need to have jQuery installed. Thanks to Kenneth Howe for pointing out that I could improve the code for excluding a jQuery function.

Explaining the algorithm

Lets use a randomly generated Visa credit card number 4539300916139765

Step 1 : Remove the last number from the credit card number | 4 5 3 9 3 0 0 9 1 6 1 3 9 7 6

Step 2 : Reverse the numbers | 6 7 9 3 1 6 1 9 0 0 3 9 3 5 4

Step 3 : Multiply each odd number | 12 7 18 3 2 6 2 9 0 0 6 9 6 5 8

Step 4 : Each number over 9 needs to be subtracted by 9 |  3 7 9 3 2 6 2 9 0 0 6 9 6 5 8

Step 5 : Count all numbers together | 75

Step 6 : Add the last digit of the credit card (5) with the total sum (75) | 80

Step 7 : If the digit you have is a multiple of 10 than the credit card is valid 8 * 10 is 80

The javascript long version for explanation purpose

 Short version for production use

 

Sponsored Links

Comments

One thought on “Validating credit cards with javascript using Luhn Algorithm

Leave a Reply

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

Follow me on Google+

Google Shopping Data Feed Generator

Sponsored Links

Hire Me