Skip to content

Instantly share code, notes, and snippets.

@Walkman100
Created August 16, 2021 15:26
Show Gist options
  • Save Walkman100/efc7293cb782fa72849a79617c7e01ff to your computer and use it in GitHub Desktop.
Save Walkman100/efc7293cb782fa72849a79617c7e01ff to your computer and use it in GitHub Desktop.
public (bool, string) Validate(string idNumber) {
if (!long.TryParse(idNumber, out _))
return (false, "Not a number");
if (idNumber.Length != 13)
return (false, "Must be 13 digits long");
int month = int.Parse($"{idNumber[2]}{idNumber[3]}");
if (month < 1 || month > 12)
return (false, "Incorrect Month Number");
int day = int.Parse($"{idNumber[4]}{idNumber[5]}");
if (day < 1 || day > 31)
return (false, "Incorrect Day Number");
if (idNumber[10] != '0' && idNumber[10] != '1')
return (false, "Incorrect Citizenship Number");
return LuhnChecksum(idNumber);
}
private (bool, string) LuhnChecksum(string idNumber) {
int oddResult = int.Parse(idNumber[0].ToString()) +
int.Parse(idNumber[2].ToString()) +
int.Parse(idNumber[4].ToString()) +
int.Parse(idNumber[6].ToString()) +
int.Parse(idNumber[8].ToString()) +
int.Parse(idNumber[10].ToString());
int evenResult = int.Parse($"{idNumber[1]}{idNumber[3]}{idNumber[5]}{idNumber[7]}{idNumber[9]}{idNumber[11]}") * 2;
string evenResultString = evenResult.ToString();
evenResult = 0;
foreach (var c in evenResultString) {
evenResult += int.Parse(c.ToString());
}
int both = oddResult + evenResult;
int lastdigit = both % 10; // % 10 gets the last digit
lastdigit = 10 - lastdigit;
if (lastdigit.ToString().Last() == idNumber[12])
return (true, null);
else
return (false, $"Checksum failed ({lastdigit.ToString().Last()} != {idNumber[12]})");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment