Created
December 11, 2018 14:55
-
-
Save jonathansanchez/f85c539b6272cd60c89a69a5a1381e4c to your computer and use it in GitHub Desktop.
Example validation for chilean Rut. (credit https://gist.github.com/punchi/3a5c44e7aa7ac0609ce9e53365572541)
This file contains hidden or 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
<?php | |
final class Rut { | |
/** | |
* Check a valid Rut | |
* @param string $rut | |
* @return boolean | |
*/ | |
public static function validate(string $rut): bool | |
{ | |
if (!preg_match("/^[0-9.]+[-]?+[0-9kK]{1}/", $rut)) { | |
return false; | |
} | |
$rut = preg_replace('/[.-]/i', '', $rut); | |
$dv = substr($rut, -1); | |
$number = substr($rut, 0, strlen($rut) - 1); | |
$i = 2; | |
$sum = 0; | |
foreach (array_reverse(str_split($number)) as $v) { | |
if ($i == 8) { | |
$i = 2; | |
} | |
$sum += $v * $i; | |
++$i; | |
} | |
$dvr = 11 - ($sum % 11); | |
if ($dvr == 11) { | |
$dvr = 0; | |
} | |
if ($dvr == 10) { | |
$dvr = 'K'; | |
} | |
if ($dvr == strtoupper($dv)) { | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment