这里以校验菜单类型必须在指定范围内为例:
创建规则
#支持Artisan命令行创建
root@7340a0562010:/var/www/ogenes/Genes-Admin# php artisan make:rule IsMenuType
//type 须在指定范围内
public function passes($attribute, $value)
{
return array_key_exists($value, MenuService::MENU_TYPE_OPTION);
}
定义报错信息
# app/Rules/IsMenuType.php
public function message()
{
//这里可以直接返回报错信息,也可使用翻译文案
return trans('validation.is_menu_type');
}
#翻译在 validation 中
'is_menu_type' => 'The :attribute must be a valid menu type.',//lang/en/validation.php
'is_menu_type' => ':attribute 超过固定范围.',//lang/zh_CN/validation.php
'is_menu_type' => ':attribute 超過固定範圍.',//lang/zh_HK/validation.php
应用
#vim app/Http/Requests/Menu/SaveRequest.php
public function rules(): array
{
return [
'type' => ['required', new IsMenuType()],
'name' => ['required', 'string'],
'path' => ['required', 'string'],
'component' => ['required', 'string'],
];
}