Last active
May 8, 2023 05:13
-
-
Save dehghani-mehdi/2af3d913786d8b1b286f9c28cc75d5f4 to your computer and use it in GitHub Desktop.
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
// 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