Last active
October 25, 2023 16:43
-
-
Save dlnsk/fe0290c0d6746403ebe0450a1388a876 to your computer and use it in GitHub Desktop.
Правило для проверки валидности ИНН (Laravel)
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 Inn implements Rule | |
{ | |
/** | |
* Определяет соответствует ли значение данному правилу валидации | |
* | |
* @param string $attribute | |
* @param mixed $value | |
* @return bool | |
*/ | |
public function passes($attribute, $value) | |
{ | |
// Коэффициенты контрольной суммы | |
$k = [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8]; | |
// Контрольные суммы | |
$n1 = $n2 = 0; | |
preg_match_all("/\d/", $value, $out, PREG_PATTERN_ORDER); | |
// Превращаем символы в числа | |
$digs = array_map(function($a) { | |
return +$a; | |
}, $out[0]); | |
// Вычисляем две контрольные цифры (коэффициенты используются со сдвигом) | |
if (count($digs) == 12) { | |
for($i = 0; $i < 11; $i++) { | |
$n2 += $i < 10 ? $digs[$i] * $k[$i+1] : 0; // Нужны только первый десять | |
$n1 += $digs[$i] * $k[$i]; | |
} | |
// Дополнительно находим остаток от деления на 10, чтобы осталась одна цифра | |
if (($n2 % 11) % 10 != $digs[10] || ($n1 % 11) % 10 != $digs[11]) { | |
return false; | |
} | |
} else { | |
return false; | |
} | |
return true; | |
} | |
/** | |
* Get the validation error message. | |
* | |
* @return string | |
*/ | |
public function message() | |
{ | |
return trans('validation.inn'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment