Skip to content

Instantly share code, notes, and snippets.

@dehghani-mehdi
Last active May 8, 2023 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dehghani-mehdi/2af3d913786d8b1b286f9c28cc75d5f4 to your computer and use it in GitHub Desktop.
Save dehghani-mehdi/2af3d913786d8b1b286f9c28cc75d5f4 to your computer and use it in GitHub Desktop.
// based on js version -> https://gist.github.com/dehghani-mehdi/df7f216d8031abad8c911b8117b7000e
public bool IsValidNationalCode(string value)
{
// extract only numbers form the value
value = new string(value?.Where(char.IsDigit).ToArray());
if (value.Length != 10 || Regex.IsMatch(value, @"(\d)(\1){9}")) return false;
var sum = 0;
var chars = value.ToCharArray();
var lastDigit = 0;
var remainder = 0;
for (var i = 0; i < 9; i++) sum += int.Parse(chars[i].ToString()) * (10 - i);
remainder = sum % 11;
lastDigit = remainder < 2 ? remainder : 11 - remainder;
return int.Parse(chars[9].ToString()) == lastDigit;
}
// usage
IsValidNationalCode("0797564411"); // -> true
IsValidNationalCode("0797564401"); // -> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment