// 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;
}
Posted: March 18, 2023
Return to the snippets listing