Last active
August 18, 2020 05:57
-
-
Save mirhmousavi/b4aa614393f0ad9793d125fba887da8c to your computer and use it in GitHub Desktop.
Iranian National Code Validator
This file contains 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
def check(code): | |
"""This is the python version of the javascript function from `https://www.samanese.ir/checknin` | |
for validating iranian national code | |
function validateNIN(snin) { | |
// if string nin length is less than 10 character | |
if (snin.length < 10) { | |
// wrong nin | |
return false; | |
} else { | |
// check for valid pattern | |
if (snin == '0000000000' || snin == '1111111111' || snin == '2222222222' || snin == '3333333333' || snin == '4444444444' || snin == '5555555555' || snin == '6666666666' || snin == '7777777777' || snin == '8888888888' || snin == '9999999999') { | |
return false; | |
} else { | |
// check for parity with refahi.ir check function | |
var c = parseInt(snin.charAt(9)); | |
var n = parseInt(snin.charAt(0)) * 10 + | |
parseInt(snin.charAt(1)) * 9 + | |
parseInt(snin.charAt(2)) * 8 + | |
parseInt(snin.charAt(3)) * 7 + | |
parseInt(snin.charAt(4)) * 6 + | |
parseInt(snin.charAt(5)) * 5 + | |
parseInt(snin.charAt(6)) * 4 + | |
parseInt(snin.charAt(7)) * 3 + | |
parseInt(snin.charAt(8)) * 2; | |
var r = n - parseInt(n / 11) * 11; | |
// return (r == 0 && r == c) || (r == 1 && c == 1) || (r > 1 && c == 11 - r); | |
if ((r == 0 && r == c) || (r == 1 && c == 1) || (r > 1 && c == 11 - r)) { | |
return true; | |
} else { | |
return false | |
} | |
} | |
} | |
} | |
""" | |
if len(code) != 10: | |
return False | |
if len(set(code)) == 1: | |
return False | |
c = int(code[9]) | |
n = ( | |
int(code[0]) * 10 | |
+ int(code[1]) * 9 | |
+ int(code[2]) * 8 | |
+ int(code[3]) * 7 | |
+ int(code[4]) * 6 | |
+ int(code[5]) * 5 | |
+ int(code[6]) * 4 | |
+ int(code[7]) * 3 | |
+ int(code[8]) * 2 | |
) | |
r = n - int(n / 11) * 11 | |
if (r == 0 and r == c) or (r == 1 and c == 1) or (r > 1 and (c == 11 - r)): | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment