Credit card validation

We’ve been updating the e-commerce side of the website to work with Maestro cards in the near future. As a result, I’ve had my first delve into card processing and some of the simple techniques that you can use to validate a card before submitting details to a bank / online card processing service.

The strange sounding Luhn Algorithm is used as a quick checksum of the credit card digits (and a few other things) and will detect most transposed digits.

The code to check if the credit card number is valid used to check if the card number was less than or equal to 16 digits long. However,we’ve found that the PAN can be between 12 – 19 digits (International Maestro cards can be 12). So after a bit of testing we discovered that the Luhn algorithm works regardless as long as the card number is valid.

public override bool Validate( string number )
{
valid = false;
if (number != null)
{
int sum = 0;
int len = number.Length;
for (int i = len - 1; i >= 0; i--)
{
byte b = Byte.Parse(number[i].ToString());
if ((i % 2) == len % 2)
{
int n = b * 2;
sum += (n / 10) + (n % 10);
}
else
{
sum += b;
}
}
valid = (sum % 10 == 0);
if (!IsValid)
{
error = "The card number is invalid";
}
}
return valid;
}

To test your validation checks, there are several ‘safe’ credit card numbers which are defined as test cards and won’t charge anyone for your attempts.
Here are a few I’ve collected in one place:

Credit Card Type Test Account Number
American Express 3782 8224 6310 005
Discover 6011 1111 1111 1117
JCB 3566 1111 1111 1113
Laser 6304 9850 2809 0561 515
Maestro (International) 5033 9619 8909 17
  5868 2416 0825 5333 38
Maestro (UK Domestic)  
Issue number not required: 6759 4111 0000 0008
18 digits: 6759 0000 0000 0000 00
19 digits: 6759 0000 0000 0000 000
MasterCard 5555 5555 5555 4444
Solo  
Issue number not required: 6334 5898 9800 0001
One-digit issue number required: 6767 8200 9988 0077 06
Two-digit issue number required: 6334 9711 1111 1114
UATP 1354 1234 5678 911
Visa 4111 1111 1111 1111

The usual disclaimers about checking that your card processing service does handle you using test numbers, and that this post is for information only and no liability is accepted if you choose to not double check the details before using them and incurr any charges or damages.

3 thoughts on “Credit card validation”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.