Last active
March 31, 2024 08:41
-
-
Save DRSDavidSoft/4cd1ede79656a91746bc1806cdee0675 to your computer and use it in GitHub Desktop.
Example js code to validate Iran's National ID also known as the Code Melli – کد نمونه جاوا اسکریپت برای بررسی صحت و تأیید کد ملی.
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
/** | |
* Example Javascript snippet to validate Iran's National ID (Code Melli) | |
* https://math.stackexchange.com/q/2740295/285467 | |
* David Refoua <David@Refoua.me> | |
*/ | |
function validateNID( code ) | |
{ | |
var str = code.toString(); | |
// validate the string length and value | |
var strLen = str.length, strVal = parseInt(str); | |
if ( strLen < 8 || strLen > 10 || isNaN(strVal) || strVal == 0 ) | |
return false; | |
// make sure the string is padded with zeros | |
while ( str.length < 10 ) str = '0' + str; | |
// invalidate consecutive arrangement of the same digit | |
if ( str.match(/^(\d)\1+$/g) ) return false; | |
var checkDigit = parseInt(str.slice(-1)), // rightmost digit | |
str = str.slice(0, -1); // remove the check digit | |
for ( var sum = 0, i = str.length; i > 0; i-- ) | |
sum += (i+1) * str.substr( -i, 1 ); | |
// calculate sum modulo 11 | |
var mod = sum % 11; | |
return ( mod < 2 && mod === checkDigit ) || ( mod >= 2 && mod + checkDigit === 11); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment