Last active
October 7, 2022 17:55
-
-
Save IsaacAndres/f62e3f88a2cdd2070d564cc50b1374c5 to your computer and use it in GitHub Desktop.
Larevel Rule Validate RUT
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
<?php | |
namespace App\Rules; | |
use Illuminate\Contracts\Validation\Rule; | |
class Rut implements Rule | |
{ | |
/** | |
* Create a new rule instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
// | |
} | |
/** | |
* Determine if the validation rule passes. | |
* | |
* @param string $attribute | |
* @param mixed $value | |
* @return bool | |
*/ | |
public function passes($attribute, $value) | |
{ | |
$rut = $value; | |
// Verifica que no esté vacio y que el string sea de tamaño mayor a 3 carácteres(1-9) | |
if ((empty($rut)) || strlen($rut) < 3) { | |
return false; | |
} | |
// Quitar los últimos 2 valores (el guión y el dígito verificador) y luego verificar que sólo sea | |
// numérico | |
$parteNumerica = str_replace(substr($rut, -2, 2), '', $rut); | |
if (!preg_match("/^[0-9]*$/", $parteNumerica)) { | |
return false; | |
} | |
$guionYVerificador = substr($rut, -2, 2); | |
// Verifica que el guion y dígito verificador tengan un largo de 2. | |
if (strlen($guionYVerificador) != 2) { | |
return false; | |
} | |
// obliga a que el dígito verificador tenga la forma -[0-9] o -[kK] | |
if (!preg_match('/(^[-]{1}+[0-9kK]).{0}$/', $guionYVerificador)) { | |
return false; | |
} | |
// Valida que sólo sean números, excepto el último dígito que pueda ser k | |
if (!preg_match("/^[0-9.]+[-]?+[0-9kK]{1}/", $rut)) { | |
return false; | |
} | |
$rutV = preg_replace('/[\.\-]/i', '', $rut); | |
$dv = substr($rutV, -1); | |
$numero = substr($rutV, 0, strlen($rutV) - 1); | |
$i = 2; | |
$suma = 0; | |
foreach (array_reverse(str_split($numero)) as $v) { | |
if ($i == 8) { | |
$i = 2; | |
} | |
$suma += $v * $i; | |
++$i; | |
} | |
$dvr = 11 - ($suma % 11); | |
if ($dvr == 11) { | |
$dvr = 0; | |
} | |
if ($dvr == 10) { | |
$dvr = 'K'; | |
} | |
if ($dvr == strtoupper($dv)) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* Get the validation error message. | |
* | |
* @return string | |
*/ | |
public function message() | |
{ | |
return 'El RUT ingresado no es válido.'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment