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;
}

4 comments:

  1. I really impressed after read this because of some quality work and informative thoughts . I just wanna say thanks for the writer and wish you all the best for coming!. dlrcollectionagency.com is a collection agency for small business

    ReplyDelete
  2. Thank you again for all the knowledge you distribute,Good post. I was very interested in the article, it's quite inspiring I should admit. I like visiting you site since I always come across interesting articles like this one.Great Job, I greatly appreciate that.Do Keep sharing! Regards, Cool roblox usernames

    ReplyDelete
  3. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. Vclub

    ReplyDelete
  4. First of all you need to distribute all the instruction letters and vouchers to your merchants regarding the services. Selling Credit Card Machines

    ReplyDelete