symfony - 如何在 Symfony 4 中验证数组数组

标签 symfony symfony4

我想知道如何在 symfony 中验证数组数组。
我的验证规则是:

  • 用户 - NotBlank
  • 日期 - 日期和 NotBlank
  • 礼物 - NotBlank

  • 到目前为止,我已经这样做了:
    $validator = Validation::createValidator();
    
    $constraint = new Assert\Collection(array(
            'user' => new Assert\NotBlank(),
            'date' => new Assert\Date(),
            'present' => new Assert\NotBlank()
    ));
    
    $violations = $validator->validate($request->request->get('absences')[0], $constraint);
    

    但问题是它只允许验证单个数组,例如。$request->request->get('absences')[0] .

    这是数组的样子:

    enter image description here

    最佳答案

    你必须把Collection内部约束 All约束:

    When applied to an array (or Traversable object), this constraint allows you to apply a collection of constraints to each element of the array.


    因此,您的代码可能如下所示:
    $constraint = new Assert\All(['constraints' => [
        new Assert\Collection([
            'user' => new Assert\NotBlank(),
            'date' => new Assert\Date(),
            'present' => new Assert\NotBlank()
        ])
    ]]);
    
    更新:如果你想为此使用注释,它看起来像这样:
    @Assert\All(
        constraints={
            @Assert\Collection(
                fields={
                    "user"=@Assert\NotBlank(),
                    "date"=@Assert\Date(),
                    "present"=@Assert\NotBlank()
                }
            )
        }
    )
    

    关于symfony - 如何在 Symfony 4 中验证数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53374344/

    相关文章:

    php - Symfony2 显示数据库字段中的 twig 函数

    forms - Symfony 4 表单集合类型 : make FileType element required for new rows only

    php - 错误 : "An exception has been thrown during the rendering of a template"

    php - Symfony 服务析构函数被多次调用

    symfony - 使用 FosUserBundle 创建管理员用户

    testing - 如何拥有多个不同配置的测试环境?

    forms - Symfony 4 处理 null DateType 表单字段

    php - 使用 Composer 创建 Symfony 项目

    symfony - FOSUserBundle登录时的区域设置切换

    php - Doctrine 说我应该在显式字段中拆分参数,但我的 ID 为空