This example shows how to validate a credit card number to protect against typos.
The program first verifies that the number has 16 digits. It then checks the digits starting from the end. If a digit's position in the number is odd (numbered starting with digit 1 at the end), the program adds its value to a checksum value. If the digit's position is even, the program doubles it and adds the resulting value's digit(s) to the checksum value.
For example, suppose the number is 1234567890123456. The checksum value would be:
6 + [2*5] + 4 + [2*3] + 2 + [2*1] + 0 + [2*9] +
8 + [2*7] + 6 + [2*5] + 4 + [2*3] + 2 + [2*1] =
6 + [10] + 4 + [6] + 2 + [2] + 0 + [18] +
8 + [14] + 6 + [10] + 4 + [6] + 2 + [2] =
6 + 1+0 + 4 + 6 + 2 + 2 + 0 + 1+8 +
8 + 1+4 + 6 + 1+0 + 4 + 6 + 2 + 2 =
64
If the card number is valid, the result will be a multiple of 10. This example gives 64 which is not a multiple of 10 so this is an invalid number.
Different types of credit cards have different prefixes. For example, Visa cards all begin with the digit 4. After the program verifies that the number has a correct checksum, it checks that the user entered the right card type for the number's prefix.
Note that this test helps protect against a user incorrectly entering a credit card number. It doesn't prevent someone from cooking up a nonexistent number that has a valid checksum and prefix. That's pretty easy to do.
