多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 引入组件包 ~~~ composer require hyperf/validation composer require hyperf/translation ~~~ ## 自动验证方式 ### 发布配置文件 ~~~ // 发布 Translation 组件的文件 php bin/hyperf.php vendor:publish hyperf/translation // 发布验证器组件的文件 php bin/hyperf.php vendor:publish hyperf/validation ~~~ ### 添加中间件 > 在`config\autoload\middlewares.php`文件中添加验证中间件 ~~~ return [ 'http' => [ \Hyperf\Validation\Middleware\ValidationMiddleware::class ], ]; ~~~ ### 添加异常处理器 ~~~ return [ 'handler' => [ 'http' => [ \Hyperf\Validation\ValidationExceptionHandler::class, ], ], ]; ~~~ ### 生成验证类 > 命令生成 ~~~ php bin/hyperf.php gen:request FooRequest ~~~ > 生成类如下 ~~~ declare(strict_types=1); namespace App\Request; use Hyperf\Validation\Request\FormRequest; class FooRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return true; } /** * Get the validation rules that apply to the request. */ public function rules(): array { return [ 'foo' => 'required|max:255', 'bar' => 'required', ]; } public function messages(): array { return [ 'foo.required' => 'foo is required', 'bar.required' => 'bar is required', ]; } } ~~~ ### Controller 中使用 > 如果验证不通过,则会被ValidationExceptionHandler拦截,返回错误的信息,如果想返回json信息,请自定修改这个异常类 ~~~ public function test(FooRequest $request){ $validated = $request->validated(); var_dump($validated); } ~~~ ## 手动验证方式 ### Controller 中使用 ~~~ public function test(RequestInterface $request) { $validator = $this->validationFactory->make( $request->all(), [ 'foo' => 'required', 'bar' => 'required', ], [ 'foo.required' => 'foo is required', 'bar.required' => 'bar is required', ] ); var_dump($validator->fails()); if ($validator->fails()){ // Handle exception $errorMessage = $validator->errors()->first(); var_dump($errorMessage); } } ~~~ ## 表单验证规则大全 > 参考 https://learnku.com/docs/laravel/5.4/validation/1234#189a36