feat: implement server-side validation for mobile numbers and national codes across multiple endpoints
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Shared\Service;
|
||||
|
||||
/**
|
||||
* اعتبارسنجیِ مشترکِ سمت سرور برای ورودیهای رایج (موبایل ایران، کد ملی).
|
||||
* معادلِ منطقِ سمت فرانت تا رفتار یکدست بماند.
|
||||
*/
|
||||
final class InputValidator
|
||||
{
|
||||
public static function isValidIranMobile(string $mobile): bool
|
||||
{
|
||||
return (bool) preg_match('/^09\d{9}$/', self::toEnglishDigits($mobile));
|
||||
}
|
||||
|
||||
/** کد ملی ایران: ۱۰ رقم + الگوریتم رقم کنترلی؛ ارقام یکسان نامعتبر. */
|
||||
public static function isValidIranNationalCode(string $code): bool
|
||||
{
|
||||
$code = self::toEnglishDigits($code);
|
||||
if (!preg_match('/^\d{10}$/', $code)) {
|
||||
return false;
|
||||
}
|
||||
if (preg_match('/^(\d)\1{9}$/', $code)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$check = (int) $code[9];
|
||||
$sum = 0;
|
||||
for ($i = 0; $i < 9; $i++) {
|
||||
$sum += (int) $code[$i] * (10 - $i);
|
||||
}
|
||||
$r = $sum % 11;
|
||||
|
||||
return $r < 2 ? $check === $r : $check === 11 - $r;
|
||||
}
|
||||
|
||||
public static function toEnglishDigits(string $s): string
|
||||
{
|
||||
return strtr($s, [
|
||||
'۰' => '0', '۱' => '1', '۲' => '2', '۳' => '3', '۴' => '4',
|
||||
'۵' => '5', '۶' => '6', '۷' => '7', '۸' => '8', '۹' => '9',
|
||||
'٠' => '0', '١' => '1', '٢' => '2', '٣' => '3', '٤' => '4',
|
||||
'٥' => '5', '٦' => '6', '٧' => '7', '٨' => '8', '٩' => '9',
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user