By Michael Mumcuoglu
Here is an updated to the article "Low Cost Of Verifying Credit Card Numbers In C#" originally written by Raju Pericharla.
Update include:
1. It is 12 lines instead of 100.
2. It is a reusable method that receives the credit-number as a parameter and returns true/false instead of being tightly-coupled to the win-form's code.
3. It is much faster (takes about half of the time to run)
///
/// Validates a credit-card number using the mod-10 algorithm.
///
/// The credit-card number as string
/// True if the credit-card is valid, false otherwise.
public static bool IsCreditCardValid(string credit) {
int[] even = new int[] {0, 2, 4, 6, 8, 1, 3, 5, 7, 9};
char[] creditArray = credit.ToCharArray();
int creditLength = credit.Length;
int sum = 0;
for (int i = 1; i <= creditLength; ++i) {
if (i % 2 == 1) {
sum += creditArray[creditLength-i] - '0';
} else {
sum += even[creditArray[creditLength-i] - '0'];
}
}
return (sum % 10 == 0);
}