validate visa and mastercard credit cards in csharp

To validate Visa and Mastercard credit cards in C#, we can make use of regular expressions. Here is the code:

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

    // Visa regex pattern
    string visaPattern = @"^4[0-9]{12}(?:[0-9]{3})?$";
    // Mastercard regex pattern
    string mastercardPattern = @"^5[1-5][0-9]{14}$";

    // Check if the credit card number matches the Visa or Mastercard pattern
    if (Regex.IsMatch(creditCardNumber, visaPattern) || Regex.IsMatch(creditCardNumber, mastercardPattern))
    {
        return true;
    }
    else
    {
        return false;
    }
}
636 chars
21 lines

To use this method, simply pass in the credit card number as a string parameter and it will return a boolean indicating whether the number is a valid Visa or Mastercard credit card number.

gistlibby LogSnag