Skip to content

Instantly share code, notes, and snippets.

@dehghani-mehdi
Last active August 4, 2023 00:27
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dehghani-mehdi/df7f216d8031abad8c911b8117b7000e to your computer and use it in GitHub Desktop.
Save dehghani-mehdi/df7f216d8031abad8c911b8117b7000e to your computer and use it in GitHub Desktop.
Validate Iranian national code in JavaScript - بررسی صحت کد ملی در جاوا اسکریپت
// C# version -> https://gist.github.com/dehghani-mehdi/2af3d913786d8b1b286f9c28cc75d5f4
var isValidNationalCode = function(code) {
if (code.length !== 10 || /(\d)(\1){9}/.test(code)) return false;
var sum = 0,
chars = code.split(''),
lastDigit,
remainder;
for (var i = 0; i < 9; i++) sum += +chars[i] * (10 - i);
remainder = sum % 11;
lastDigit = remainder < 2 ? remainder : 11 - remainder;
return +chars[9] === lastDigit;
};
// ES6 version
const isValidNationalCode = code => {
if (code.length !== 10 || /(\d)(\1){9}/.test(code)) return false;
let sum = 0,
chars = code.split(''),
lastDigit,
remainder;
for (let i = 0; i < 9; i++) sum += +chars[i] * (10 - i);
remainder = sum % 11;
lastDigit = remainder < 2 ? remainder : 11 - remainder;
return +chars[9] === lastDigit;
};
// usage
isValidNationalCode('0060647531');
@abbasmoosavi
Copy link

Thanks, safe my day, and better code is:
const isValidNationalCode = value => {
if (value.length !== 10 || /(\d)(\1){9}/.test(value)) return false;

let sum = 0;
const chars = value.split('');

for (let i = 0; i < 9; i += 1) sum += +chars[i] * (10 - i);

let lastDigit = null;
const remainder = sum % 11;

lastDigit = remainder < 2 ? remainder : 11 - remainder;

return +chars[9] === lastDigit;

};

@miladbayee
Copy link

thanks mr abbasmoosavi,I think yon can write better code in for loop:

for (let i = 0; i < 9; i++) sum += +chars[i] * (10 - i);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment