Credit Card Validation Using Luhn 10 in C#

Description: Validates if a supplied credit card number is possibly valid/invalid using the Luhn 10 algorithm.
Tested Platform: .NET 4.0, Visual Studio 2010, Windows 7
Language: C#
// Validate if credit card number could be valid using the Luhn 10 Algorithm
public static bool LuhnTest(string ccNumber)  {
    if (System.Text.RegularExpressions.Regex.IsMatch(ccNumber, @"^d+$")) {
        int sum = 0;
        for (int i = ccNumber.Length - 1; i >= 0; i--)  {
            int digit = int.Parse(ccNumber[i].ToString());

            // For even numbers add the digit as is.
            if ((i % 2) == 0) {
                        sum += digit;
            }
            else  {
                        // For odd digits, multiply by 2 and if that
                        // multiplication is greater than 10, subtract 9
                        // which gives us the sum of the two digits.
                        sum += (2 * digit);
                        if (digit >= 5) { sum -= 9; }
            }
        }

        return ((sum % 10) == 0);
    }

    return false;
}

Submitted: March 06, 2013

Return to the snippets listing