how to validate a credit card number in csharp

main.cs
public static bool ValidateCreditCardNumber(string creditCardNumber)
{
    // Remove any spaces or dashes from the credit card number
    creditCardNumber = creditCardNumber.Replace(" ", "").Replace("-", "");

    // Check if the credit card number contains only digits
    if (!creditCardNumber.All(char.IsDigit))
    {
        return false;
    }

    // Check if the credit card number is of valid length (13-16 digits)
    if (creditCardNumber.Length < 13 || creditCardNumber.Length > 16)
    {
        return false;
    }

    // Check if the credit card number passes the Luhn algorithm
    int sum = 0;
    bool alternate = false;
    for (int i = creditCardNumber.Length - 1; i >= 0; i--)
    {
        int digit = int.Parse(creditCardNumber[i].ToString());

        if (alternate)
        {
            digit *= 2;
            if (digit > 9)
            {
                digit = (digit / 10) + (digit % 10);
            }
        }

        sum += digit;
        alternate = !alternate;
    }

    if (sum % 10 != 0)
    {
        return false;
    }

    // If all checks pass, then the credit card number is valid
    return true;
}
1145 chars
46 lines

Example usage:

main.cs
string creditCardNumber = "1234-5678-9012-3456";
bool isValid = ValidateCreditCardNumber(creditCardNumber);
Console.WriteLine("Is valid credit card number: " + isValid);
170 chars
4 lines

gistlibby LogSnag