我正在尝试对传入的一些查询字符串参数执行一些验证。我想做三件事:
我想重新使用尽可能多的内置Symfony验证器功能来执行此操作,到目前为止有类似下面的代码(但它不起作用)。有人会有建议吗?
相关参考文献:
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints\Collection
use Symfony\Component\Validator\Constraints\Type
代码:
public function testingAction(Request $request)
{
$parameters = $request->query->all();
// for this example, assume that $parameters contains 'firstname'=>123
$collectionConstraint = new Collection(array(
'firstname' => new Type(array('type'=>'string'))
);
$errors = $this->container->get('validator')->validate($parameters, $collectionConstraint);
return new Response('<html><body><pre>' . print_r($errors, TRUE) . '</pre></body></html>');
}
答案 0 :(得分:0)
Symfony验证适用于实体类。您需要使用验证注释为数据创建实体类。
// src/Entity/Author.php
// ...
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
/**
* @Assert\NotBlank()
*/
public $name;
}
//然后将此类用于您的数据
use src/Entity/Auther.php;
public function testingAction(Request $request)
{
$parameters = $request->query->all();
$auther = new Auther();
$auther->setName($paramater['name']);
$errors = $this->container->get('validator')->validate($auther);
return new Response('<html><body><pre>' . print_r($errors, TRUE) . '</pre></body></html>');
}
请关注symfony链接https://symfony.com/doc/current/validation.html