Created
April 21, 2024 13:08
-
-
Save ravahdati/57708ea0a87afb9868ee3b1d24ca8acf to your computer and use it in GitHub Desktop.
Iranian National Code Validation - PHP
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
/** | |
* Check the validity of an Iranian national code | |
* | |
* @param string $code The national code to be validated. | |
* @return bool True if the code is valid, false otherwise. | |
*/ | |
function check_national_code($code) | |
{ | |
// Check if the input code is a 10-digit number | |
if (!preg_match('/^[0-9]{10}$/', $code)) { | |
return false; | |
} | |
// Check for repetitive patterns like "0000000000" | |
for ($i = 0; $i < 10; $i++) { | |
if (preg_match('/^'.$i.'{10}$/', $code)) { | |
return false; | |
} | |
} | |
// Calculate the sum based on the algorithm | |
for ($i = 0, $sum = 0; $i < 9; $i++) { | |
$sum += ((10 - $i) * intval(substr($code, $i, 1))); | |
} | |
// Validate the code using modulus operation | |
$ret = $sum % 11; | |
$parity = intval(substr($code, 9, 1)); | |
if (($ret < 2 && $ret == $parity) || ($ret >= 2 && $ret == 11 - $parity)) { | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment