Skip to content

Instantly share code, notes, and snippets.

@kpol
Last active December 11, 2018 21:34
Show Gist options
  • Select an option

  • Save kpol/f857c3cd95a4a0a0ac090d5ee2711f37 to your computer and use it in GitHub Desktop.

Select an option

Save kpol/f857c3cd95a4a0a0ac090d5ee2711f37 to your computer and use it in GitHub Desktop.
Checks number against Luhn algorithm/
private static bool IsValidCreditCardNumber(string creditCardNumber)
{
// based on Luhn algorithm
// https://en.wikipedia.org/wiki/Luhn_algorithm
if (creditCardNumber == null) throw new ArgumentNullException(nameof(creditCardNumber));
// credit card number length must be between [12, 19]
if (creditCardNumber.Length < 12 || creditCardNumber.Length > 19)
{
return false;
}
int sum = 0;
bool alternate = false;
for (int i = creditCardNumber.Length - 1; i >= 0; i--)
{
var n = creditCardNumber[i] - '0';
if (n < 0 || n > 9)
{
return false;
}
if (alternate)
{
n *= 2;
if (n >= 10)
{
n -= 9;
}
}
sum += n;
alternate = !alternate;
}
return sum % 10 == 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment