Validating credit card numbers: The Luhn algorithm
December 22, 2005 /
Filed under: JavaScript, Tutorials
It’s interesting how credit card numbers are validated. Below is a description of the formula used to validate a credit card number.
How it’s doneHere’s how it’s done:
Examining the processHere’s an example credit card number, that I just made up (maybe I’ll get lucky and it will validate):
Let’s do the formula on this number. First, we reverse the entire string of numbers:
Next, we double every second digit, starting with the second digit:
To clarify that step - I started with the number 9, which is the second number from the left. I doubled that number. The next number to double is 0 - which is the last digit of the first four numbers (2900). I doubled that number, then I went to the number 8. I continued this trend until the end of all of the digits. The next step is to add all of the "duplicate" digits together. Again, our duplicate digits are:
We need to add all of these digits together - but remember to treat each number as a single digit. So, this is how we would add them together:
Make sense? Thought so... The sum of these numbers is 43. According to our rule, if the number is divisible by 10, it’s valid. 43 is definitely not divisible by 10 - so the credit card number is not valid. Practical applicationsSince credit card numbers are used widely on the web, it makes sense to have a script check to see if numbers are valid. This can be done with a server-side scripting language (such as PHP, ASP), or more practically (I think) is with JavaScript. The following function was extracted from a helpful JavaScript book that I use as my general reference book: Special Edition: Using JavaScript, by Paul McFedries. Comments/Mentions |
Recent Comments
Recent Music Listens
|
Wow. That's really cool! Thanks for posting this!