Last active
June 29, 2023 21:15
-
-
Save Orbis25/98c87dad4e4458a470f1fd2b6b746479 to your computer and use it in GitHub Desktop.
Validate creditcard with c#
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 ValidateCreditCard(string? creditCard) | |
{ | |
try | |
{ | |
_ = long.Parse(creditCard ?? ""); | |
} | |
catch (Exception) | |
{ | |
return false; | |
} | |
if (string.IsNullOrEmpty(creditCard)) return (false); | |
int[] digits = new int[creditCard.Length]; | |
for (int i = 0; i < creditCard.Length; i++) | |
{ | |
digits[i] = Convert.ToInt32(creditCard.Substring(i, 1)); | |
} | |
for (int i = digits.Length - 2; i >= 0; i -= 2) | |
{ | |
int results = digits[i] * 2; | |
if (results > 9) | |
{ | |
results -= 9; | |
} | |
digits[i] = results; | |
} | |
int sum = 0; | |
foreach (int digt in digits) | |
{ | |
sum += digt; | |
} | |
return (sum % 10 == 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment