symfony - 当数据在 Symfony 中作为数组传递时,如何在验证组件中使用 EqualTo 约束?
问题描述
Symfony 提供了根据https://symfony.com/doc/current/validation/raw_values.html验证数组的方法,并使用它我想使用 EqualTo 约束(https://symfony.com/doc/current/reference/constraints /EqualTo.html ) 不使用密码并确认密码大小写。请看下面的代码:
$this->constraint = new Assert\Collection([
// the keys correspond to the keys in the input array
'fields' => [
'password' =>
[
new Assert\NotBlank(['message' => 'Please enter password.']),
new Assert\Length(['min' => 5, 'minMessage' => 'Please enter password of 5 characters at least.']),
]
,
'confirm_password' =>
[
new Assert\NotBlank(['message' => 'Please enter confirm password.']),
new Assert\EqualTo(['propertyPath' => 'password']),
]
,
],
'allowMissingFields' => false,
'missingFieldsMessage' => 'Please enter value.',
]);
现在,调用它:
$this->validator = Validation::createValidator();
$this->validator->validate($input, $this->constraint, $groups);
以上不起作用。
这个想法是在准备实体之前首先验证请求的数据,然后适当地持久化实体。另外,我想将验证机制与不同的实体分开。
解决方案
而不是 EqualsTo 使用回调约束
$this->constraint = new Assert\Collection([
// the keys correspond to the keys in the input array
'fields' => [
'password' =>
[
new Assert\NotBlank(['message' => 'Please enter password.']),
new Assert\Length(['min' => 5, 'minMessage' => 'Please enter password of 5 characters at least.']),
]
,
'confirm_password' =>
[
new Assert\NotBlank(['message' => 'Please enter confirm password.']),
new Assert\Callback(['callback' => function ($value, ExecutionContext $ec) {
if ($ec->getRoot()['password'] !== $value) {
$ec->addViolation("Passwords do not match");
}
}])
]
,
],
'allowMissingFields' => false,
'missingFieldsMessage' => 'Please enter value.',
]);
推荐阅读
- c++ - Visual Studio 和 Github 如何协同工作?
- java - 如何在 Java selenium 中使用 driver.getWindowHandle()?
- java - null 检查语句是否在 java 中不起作用
- r - 在循环 R 中切片数据帧
- ios - X次后如何显示评分应用程序的对话框?
- jquery - 如何创建一个可以在检查类时从类中删除复选框的函数?
- c# - C#,我希望主线程在所有子线程结束后输出“num”,怎么做?现在我只能得到'0'
- javascript - {Signature for this request is not valid}币安提款错误
- c - 在C中找到大整数的所有质因子的更好方法?
- node.js - Class-Validator node.js 提供自定义错误