Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example js code to validate Iran's National ID also known as the Code Melli – کد نمونه جاوا اسکریپت برای بررسی صحت و تأیید کد ملی.
/**
* 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