Last active
December 11, 2018 21:34
-
-
Save kpol/f857c3cd95a4a0a0ac090d5ee2711f37 to your computer and use it in GitHub Desktop.
Checks number against Luhn algorithm/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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