【发布时间】:2018-02-06 17:15:31
【问题描述】:
我正在尝试对传入的一些查询字符串参数进行一些验证。我想做 3 件事:
- 检查名字是否通过。
- 如果通过,验证它是一个字符串。否则,抛出错误。
- 如果未通过,请指定一个默认名称。
我想尽可能多地重复使用内置的 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>');
}
【问题讨论】:
标签: php api symfony validation