【问题标题】:Symfony Optional constraints not working as expectedSymfony 可选约束未按预期工作
【发布时间】:2015-06-18 17:37:26
【问题描述】:

我目前有一个 Symfony 验证器可选约束的问题。

我需要仅在该字段已通过时才处理 parentId 规则(密钥在 ParameterBag 中),不幸的是,即使未通过,Symfony 也总是尝试验证。

public function validateParameters(ParameterBag $request, Collection $validatorRules)
{
    $validatorErrors = $this->validator->validateValue($request->all(), $validatorRules);
    if (count($validatorErrors) !== 0) {
        throw new \Exception($validatorErrors[0]->getPropertyPath() . ' - ' . $validatorErrors[0]->getMessage());
    }
    echo 'yay!';
    exit;
}

public function create(Application $app, Request $request)
{
    // check that the validation rules pass for this service
    $this->validateParameters($request->request, new Collection([
        'parentId'    => [new Assert\Optional(), new Assert\Regex(['pattern' => '/^[0-9]\d*$/'])],
        'title'       => [new Assert\NotBlank(), new Assert\Length(['min' => 3])],
        'description' => [new Assert\NotBlank()],
    ]));
    // ...............
}

任何帮助或指针将不胜感激,因为 Symfony 文档主要讨论直接针对对象进行验证,但我想针对传入的 ParameterBag 进行验证。

【问题讨论】:

    标签: php validation symfony doctrine


    【解决方案1】:

    这应该可以工作

    public function create(Application $app, Request $request)
    {
        // check that the validation rules pass for this service
        $this->validateParameters($request->request, new Collection([
            'parentId'    => new Assert\Optional([
                new Assert\Regex(['pattern' => '/^[0-9]\d*$/'])
            ]),
            'title'       => [
                new Assert\NotBlank(), 
                new Assert\Length(['min' => 3])
            ],
            'description' => new Assert\NotBlank(),
        ]));
        // ...............
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 2014-12-03
      • 2015-10-07
      相关资源
      最近更新 更多