Last active
August 27, 2024 12:49
-
-
Save dehghani-mehdi/df7f216d8031abad8c911b8117b7000e to your computer and use it in GitHub Desktop.
Validate Iranian national code in JavaScript - بررسی صحت کد ملی در جاوا اسکریپت
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
// 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'); |
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
Thanks, safe my day, and better code is:
const isValidNationalCode = value => {
if (value.length !== 10 || /(\d)(\1){9}/.test(value)) return false;
};