validate a visa credit card in csharp

Here's some code in C# that uses the Luhn algorithm to validate a Visa credit card:

main.cs
public static bool ValidateVisaCard(string cardNumber)
{
    // 1. Check if the card number is a valid Visa card (starts with 4)
    if (!cardNumber.StartsWith("4"))
    {
        return false;
    }

    // 2. Remove any spaces or dashes from the card number
    cardNumber = cardNumber.Replace(" ", "").Replace("-", "");

    // 3. Check if the card number is the correct length (13, 16, or 19 digits)
    if (cardNumber.Length != 13 && cardNumber.Length != 16 && cardNumber.Length != 19)
    {
        return false;
    }

    // 4. Use the Luhn algorithm to validate the card number
    int sum = 0;
    int digit = 0;
    int addend = 0;
    bool doubled = false;

    for (int i = cardNumber.Length - 1; i >= 0; i--)
    {
        digit = int.Parse(cardNumber.Substring(i, 1));
        if (doubled)
        {
            addend = digit * 2;
            if (addend > 9)
            {
                addend -= 9;
            }
        }
        else
        {
            addend = digit;
        }
        sum += addend;
        doubled = !doubled;
    }

    return (sum % 10) == 0;
}
1091 chars
45 lines

To use this method, simply pass in a string containing the credit card number to be validated. The method will return true if the card number is valid, and false otherwise.

gistlibby LogSnag