sharifi/symfony-validation-bundle

Symfony SymfonyValidationBundle

安装: 1

依赖: 0

建议者: 0

安全: 0

星标: 2

关注者: 4

分支: 1

开放问题: 0

类型:symfony-bundle

dev-master 2020-09-09 11:51 UTC

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();
}