How to Validate a Credit Card
Within E-Commerce sites, credit card validation is an important part of the checkout process. Quickly alerting customers to a potential information error saves time for both the customer and the business. Although most online stores today have an online payment gateway that instantly validates credit card payment, it's always faster to validate locally before sending data to a payment gateway. There are three ways you can check for a valid credit card number:
1. The number of digits in a given number:
Amex: 15 digits
Discover: 16 digits
MasterCard: 16 digits
Visa: 13 or 16 digits
2. The given number prefix:
Amex: 34 or 37
Discover: 6011
MasterCard: 51-55
Visa: 4
3. The Luhn algorithm
The algorithm was designed to protect against accidental single-digit data entry error, but we can use it as a weak number validation. All credit cards use this algorithm to validate.
Given a number:
a. Multiply every odd numbered digit by 2 and subtract by 9 if the product is greater than 9.
b. Add up all the products.
c. Add the even numbered digits to the result from step B.
d. The given number is valid if the result from step C is multiple of 10.
Example:
Given 5578-9201-2345-6789
a. 5 x 2 = 10 - 9 = 1
7 x 2 = 14 - 9 = 5
9 x 2 = 18 - 9 = 9
0 x 2 = 0
2 x 2 = 4
4 x 2 = 8
6 x 2 = 12 -9 = 3
8 x 2 = 16 - 9 = 7
b. 1 + 5 + 9 + 0 + 4 + 8 + 3 + 7 = 37
c. 5 + 8 + 2 + 1 + 3 + 5 + 7 + 9 + 37 = 77
d. 77 is not multiple of 10, therefore the above number is not valid.
You can test out the Luhn algorithm by entering a sample 15 or 16-digit number below.