Skip to content

Instantly share code, notes, and snippets.

@Orbis25
Last active June 29, 2023 21:15
Show Gist options
  • Save Orbis25/98c87dad4e4458a470f1fd2b6b746479 to your computer and use it in GitHub Desktop.
Save Orbis25/98c87dad4e4458a470f1fd2b6b746479 to your computer and use it in GitHub Desktop.
Validate creditcard with c#
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