添加正则验证助手

main
gzydong 2021-07-31 23:58:08 +08:00
parent b9d08f843a
commit c67f9877d4
2 changed files with 50 additions and 10 deletions

View File

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Helper;
/**
* 正则验证助手
*
* @package App\Helper
*/
class RegularHelper
{
// 手机号正则
const REG_PHONE = '/^1[3456789][0-9]{9}$/';
// 逗号拼接的正整数
const REG_IDS = '/^\d+(\,\d+)*$/';
// 正则别名
const REG_MAP = [
'phone' => self::REG_PHONE,
'ids' => self::REG_IDS,
];
/**
* 通过别名获取正则表达式
*
* @param string $regular 别名
* @return string
*/
public static function getAliasRegular(string $regular): string
{
return self::REG_MAP[$regular];
}
/**
* 正则验证
*
* @param string $regular 正则名称
* @param int|string $value 验证数据
* @return bool
*/
public static function verify(string $regular, $value): bool
{
return (bool)preg_match(self::getAliasRegular($regular), $value);
}
}

View File

@ -2,6 +2,7 @@
namespace App\Listener;
use App\Helper\RegularHelper;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Event\ValidatorFactoryResolved;
@ -27,20 +28,12 @@ class ValidatorFactoryResolvedListener implements ListenerInterface
// 注册了 ids 验证器(验证英文逗号拼接的整形数字字符串 例如:[1,2,3,4,5])
$validatorFactory->extend('ids', function ($attribute, $value) {
if (!is_string($value)) return false;
foreach (explode(',', $value) as $id) {
if (!check_int($id)) return false;
}
return true;
return is_string($value) && (empty($value) || RegularHelper::verify('ids', $value));
});
// 注册手机号验证器
$validatorFactory->extend('phone', function ($attribute, $value) {
if (!is_string($value)) return false;
return (bool)preg_match('/^1[3456789][0-9]{9}$/', $value);
return is_string($value) && RegularHelper::verify('phone', $value);
});
}
}