sharifi / symfony-validation-bundle
Symfony SymfonyValidationBundle
dev-master
2020-09-09 11:51 UTC
Requires
- php: ^7.4
- symfony/framework-bundle: ^4.0|^5.0
- symfony/validator: 4.0|^5.0
Requires (Dev)
- php-coveralls/php-coveralls: ^2.1
- phpunit/phpunit: ^7.1|^8.0
- sensio/framework-extra-bundle: ^5.5
- symfony/browser-kit: ^5.0
This package is auto-updated.
Last update: 2024-09-09 20:36:17 UTC
README
简介
此包允许您根据规则和限制通过表单请求验证请求参数。表单请求是包含验证逻辑的自定义请求类。
安装
您可以通过composer安装此包
composer require sharifi/symfony-validation-bundle
创建表单请求
首先,创建一个从 Sharifi\Bundle\SymfonyValidationBundle\Requests\FormRequest
继承的类,并在规则方法中添加您的验证规则
use Symfony\Component\Validator\Constraints\Length; use Symfony\Component\Validator\Constraints\NotBlank; use Sharifi\Bundle\SymfonyValidationBundle\Requests\FormRequest; class StoreBlogPost extends FormRequest { /** * Get the validation rules that apply to the request. */ protected function rules(): array { return [ 'name' => [ new Length(['max' => 255]), new NotBlank(), ], ]; } }
使用表单请求
那么,验证规则是如何评估的?您只需在控制器方法中对请求进行类型提示。在调用控制器方法之前,会验证传入的表单请求,这意味着您不需要在控制器中添加任何验证逻辑
/** * Store the incoming blog post. */ public function store(StoreBlogPost $request): Response { // The incoming request is valid... // Retrieve the validated input data... $validated = $request->validated(); }