Thursday, January 29, 2009

C# .NET 3.5 Credit card validation using Luhn formula

The following function in C# .NET 3.5 checks whether a given credit card is valid using the Mod10 or Luhn formula.

For more complete information and explanation of how the formula works, please check out this website. I based this function largely from the information I got there.

In summary the formula is as follow:
1) Double each alternative digit, starting from the second digit from the *RIGHT
2) If any digit is equal to 10 or greater, then add up the digits. e.g. "10" would be equal to "1 + 0" or "1"
3) Sum up all the digits.
4) If result is divisible by 10, then we probably have got a valid card number, otherwise it's fake.

This is a necessary, but insufficient check to verify credit card numbers generated by most financial institution. For a more complete check, you'll also need to check the first digits, to make sure they match the credit card company, eg. Master Card, may start with 51. However this is an easy check and is not a subject of this topic.

Function to check if credit card number is valid, or otherwise using Mod 10, or Luhn Formula:




public bool Mod10Check(string CreditCardNumber)
{
char[] CreditCardNumberArray = CreditCardNumber.ToCharArray();


var CreditCardDigits = new short[CreditCardNumberArray.Length];


for (int i = 0; i < CreditCardNumberArray.Length; i++)
{
CreditCardDigits[i] = short.Parse(CreditCardNumberArray[i].ToString());
}


CreditCardDigits = CreditCardDigits.Reverse().ToArray();


for (int i = 0; i < CreditCardDigits.Length; i++)
{
if (i%2 == 1)
{
CreditCardDigits[i] = (short)
(CreditCardDigits[i]*2);


if (CreditCardDigits[i]
>= 10)
{
char[] BigDigit =
CreditCardDigits[i].ToString().ToCharArray();


CreditCardDigits[i] = (short)
(short.Parse(BigDigit[0].ToString())
+ short.Parse(BigDigit[1].ToString()));
}
}
}


int SumOfDigits = CreditCardDigits.Sum(o => (int) o);


return SumOfDigits%10 == 0;
}

No comments:

Post a Comment