当数据在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 AssertCollection([
// the keys correspond to the keys in the input array
'fields' => [
'password' =>
[
new AssertNotBlank(['message' => 'Please enter password.']),
new AssertLength(['min' => 5, 'minMessage' => 'Please enter password of 5 characters at least.']),
]
,
'confirm_password' =>
[
new AssertNotBlank(['message' => 'Please enter confirm password.']),
new AssertEqualTo(['propertyPath' => 'password']),
]
,
],
'allowMissingFields' => false,
'missingFieldsMessage' => 'Please enter value.',
]);

现在,称之为:

$this->validator = Validation::createValidator();
$this->validator->validate($input, $this->constraint, $groups);

以上不起作用。

其思想是在准备实体之前首先验证请求的数据,然后适当地持久化实体。此外,我想将验证机制与不同的实体分开。

使用回调约束而不是Equals

$this->constraint = new AssertCollection([
// the keys correspond to the keys in the input array
'fields' => [
'password' =>
[
new AssertNotBlank(['message' => 'Please enter password.']),
new AssertLength(['min' => 5, 'minMessage' => 'Please enter password of 5 characters at least.']),
]
,
'confirm_password' =>
[
new AssertNotBlank(['message' => 'Please enter confirm password.']),
new AssertCallback(['callback' => function ($value, ExecutionContext $ec) {
if ($ec->getRoot()['password'] !== $value) {
$ec->addViolation("Passwords do not match");
}
}])
]
,
],
'allowMissingFields' => false,
'missingFieldsMessage' => 'Please enter value.',
]);

最新更新