Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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