Validating Credit Cards’ Numbers (not their coverage …)

In order to validate credit card numbers, you can leverage a kind of CRC (cyclic redundancy check) known with name LUHN from the name of its inventor. The algorithm is for example documented at the following URL: http://en.wikipedia.org/wiki/Luhn_algorithm. On the Internet, you will find tons of code samples for validating credit card numbers using this algorithm. However, starting from .NET 4.5 there is a native class called CreditCardAttribute, which is available in the System.ComponentModel.DataAnnotations namespace, and which is useful for validating credit card numbers. Here is a code excerpt to use it:

class Program
{
static void Main(string[] args)
{
CreditCardAttribute cc = new CreditCardAttribute();
var result = cc.IsValid(“4111-1111-1111-1111”);
Console.WriteLine(“Card valid? {0}”, result);
}
}

Enjoy!