Credit Card Validation Using Luhn Algorithm
Luhn algorithm is a checksum formula used to validate credit card numbers. It was invented by Peter luhn, a German IBM reseacher, in 1954 to protect against mistypes or reversed figures when typing credit card numbers.
How does it work?
Step 1)
Starting with the second number from the right (underlined below in blue), double every other digit as shown below.
Step 2)
Calculate the sum of all the numbers that were left behind(not underlined above) in the previous step and add them to the numbers that were doubled (numbers underlined above).
Step 3)
Calculate modulo 10 (divide by 10 and take the remainder) of the result that was computed in the previous step. If the result of the modulo operation is zero, the credit card number is valid. If the result of the modulo is anything other than zero then the number is an invalid credit card number. In our case the result is as follows:
Lets look at a slightly more complex example that covers a rule that we haven’t mentioned yet.
In this example, doubling 9 and 7 produces two digit number (18 and 14) as shown above. We need to follow an extra step when this happens and that is to convert the two digit numbers in to a one digit number by summing up the two digits. Therefore 18 becomes 1 + 8 = 9 and 14 becomes 1 + 4 = 5.
The summation of the doubled up digits with the digits left behind produces 70. Calculating modulo 10 of 70 shows that the card number is valid.
Now that you understand how this algorithm works you can add it to your application to give the user instant feedback if they mistype their credit card number.
Thank you for taking the time to read this article.