Introduction

The ultimate credit card utility provides all of the functions you need to validate and test credit cards in your .NET application, including:

IsValidNumber

GetCardTypeFromNumber

GetCardTestNumber

PassesLuhnTest

All code is provided in both C# and VB. In addition to the utility class, this project includes complete NUnit tests and a sample website for testing the code.

Background

If you have ever tried to process credit cards in your .NET applications, you know that it can be a challenge. Even if you have a good payment processor that provides a .NET SDK, there are a number of functions you're left to handle on your own, like credit card number validation and card type detection. Stop wasting time trying to piece together a utility class from all of the code snippets scattered across the Internet. I have assembled the "ultimate" credit card utility class that provides robust credit number testing, easy credit card type detection, and functions for testing credit card interfaces in your application. To top it off, the ultimate credit card utility class also comes with NUnit tests to help guarantee the code always works as expected in your important credit card applications.

In this article, we'll look at each of the functions included in the ultimate credit card utility class and explain how simple .NET concepts are used to provide powerful functionality.

Using the Code

The ultimate credit card utility class can be easily integrated into any .NET project by directly adding the .cs/.vb file or by compiling the credit card class into a separate assembly that is referenced by the application. If you have multiple applications that deal with credit cards, the best approach is to build the credit card utility class into a separate DLLl so that any updates you make in the future can easily be distributed to all of your .NET applications.

There are five basic functions in this utility class, and we'll look at each in reverse order, building up from the more complex base functions to the simple validation functions.

PassesLuhnTest

At the core of any credit card utility class is Luhn's test. This test, also known as "mod 10", was created by IBM engineer Hans Luhn in the mid-1950's, and stands as one of the easiest ways to validate that a series of numbers is valid and is not a random collection of integers. All credit card numbers should pass Luhn's test; if they don't, it's an easy way to determine that an incorrect number has been entered.

In the ultimate credit card utility, we implement a simple function that accepts a credit card number as a string and returns true if the number passes Luhn's test.

GetCardTypeFromNumber

When you shop online, you may have noticed that some sites require you to select your card type and some don't. Whether you ask for the card type explicitly or not, you can easily determine a card's type simply by analyzing the number. To do that in our utility class, we are going to leverage the power of Regular Expressions and their ability to store matches in named groups. Learning Regular Expressions can be challenging, but great resources exist that help you generate Regular Expression patterns for every situation, such as regexlib.com and Regex Buddy (software). For our utility, we will use a Regular Expression from RegExLib that validates all major credit cards.

For a complete analysis of this Regular Expression, visit this external resource. Generated by Regex Buddy, this analysis describes in English how each rule in the regex pattern works, and links to online help explaining each rule.

With our regex pattern in hand, we can now take any credit card number and determine its type.

You may have noticed that we are referring to a CreditCardTypeType in the above code. The original version of this utility was designed to work with PayPal's Web Payments Pro and that type was provided by the PayPal API. Without the PayPal API available, we can easily recreate this type for use in our utility.

IsNumberValid

Now that we've built-up some basic items needed to validate credit cards, we can create a simple function to validate card numbers. Why not access the Luhn test directly to validate credit cards? While the Luhn formula will validate that numbers appear in the correct order, it will not validate that a card is of the correct type. To make sure our utility class validates that numbers are correct and of a specific card type, we'll use the regex test and our PassesLuhnTest to ensure the supplied credit card number appears valid.

Sometimes you may just want to validate a number, though, without supplying the card type. Well, we already have a function that can determine card type by card number, so let's simply create an overloaded version of IsValidNumber that accepts a single argument (the card number).

C#

publicstaticbool IsValidNumber(string cardNum)
{
Regex cardTest = new Regex(cardRegex);
//Determine the card type based on the number
CreditCardTypeType? cardType = GetCardTypeFromNumber(cardNum);
//Call the base version of IsValidNumber and pass the
//number and card type
if (IsValidNumber(cardNum, cardType))
returntrue;
elsereturnfalse;
}

VB

PublicSharedFunction IsValidNumber(ByVal cardNum AsString) AsBooleanDim cardTest AsNew Regex(cardRegex)
'Determine the card type based on the number
Dim cardType As CreditCardTypeType = GetCardTypeFromNumber(cardNum)
'Call the base version of IsValidNumber and pass the
'number and card type
If IsValidNumber(cardNum, cardType) ThenReturnTrueElseReturnFalseEndIfEndFunction

GetCardTestNumber

We have built a comprehensive test that will check card numbers for both type and accuracy, so now we need an easy way to generate "bogus" test card numbers for use during development. If you add code to your application to detect when it's in "dev" mode (such as adding a key to the configuration files or reading the active URL), you can code your interfaces to automatically fill-in a bogus credit card number when you run your tests. That will save you from the repetitive task of manually entering valid test data when developing your application. When your application runs in production, this test should be turned-off and only customer credit card numbers should be accepted.

Testing the Utility

Any code that is going to be supporting transactions as important as processing credit cards should have a complete set of tests to ensure the code is working as expected. As such, the ultimate credit utility comes with a comprehensive set of NUnit tests that can be added to your regular testing routines.

Covering the ins and outs of creating NUnit tests is not in the scope of this article, but here is a sample NUnit test for this utility class that tests the IsValidNumber function.

Demo Website

Included in the ultimate credit card utility download is a demo website that allows you to quickly test any credit card number in the browser. The site CSS has been optimized for Firefox, but it is usable in any modern browser. To add an extra level of interactivity to the demo application, trial versions of the Telerik RadControls have been used for masked input and AJAX. The trial version of the controls can be freely used in demo applications, but a periodic trail message will appear on a random number of page loads. For more information on the commercial version of RadControls, visit http://www.telerik.com.

Conclusions

And that's it! The ultimate credit card utility class provides all of the basic functions you need to validate credit card numbers before you pass them along to your processor. The utility cannot absolutely guarantee that a number is a real credit card number before it is processed, but it can eliminate most card input errors and enable you to reduce trips to your payment processor. Hopefully, you will find this utility helpful and it will save you time on your next credit card application.

Share

About the Author

Todd Anglin is an Experts Exchange ASP.NET Master and a Telerik Technical Evangelist responsible for building a strong Telerik community across the globe. Before joining Telerik, Todd worked as a developer in a Fortune 200 financial services company in San Antonio as a Systems Analyst supporting applications on a wide range of platforms and technologies, including Unix, Windows Server, Informix, Oracle, and SQL Server. Todd graduated Magna Cum Laude with Business Honors from Mays Business School at Texas A&M University with a BBA in MIS and now resides with his wife in The Woodlands, Texas.