我如何在Optional
约束内有一个All
约束。
基本上我想验证一个键是否存在于一个数组中,它的值是一个可以包含空格或任何值的数组。
如果我省略了Collection
约束中的键,我会收到错误:
This field was not expected
我知道我可以使用allowExtraFields
,但我想验证密钥是否存在。
我虽然我将要使用:
$optional = new Constraints\Optional();
$all = new Constraints\All($optional);
但这会导致:
Fatal error: Class
'Symfony\Component\Validator\Constraints\OptionalValidator'
not found in
~\symfony\validator\Symfony\Component\Validator\ConstraintValidatorFactory.php
on line 36
这是完整的代码:
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints;
$input = [
'frames' => [
'header' => [
'test-header-1',
'test-header-2',
'',
],
'content' => [
'test-content-1',
'test-content-2',
'',
],
],
];
$optional = new Constraints\Optional();
$constraint = new Constraints\Collection([
'frames' => new Constraints\Collection([
'header' => new Constraints\All($optional),
'content' => new Constraints\All($optional),
]),
]);
$validator = Validation::createValidator();
$violations = $validator->validateValue($input, $constraint);
echo $violations;
我也试过:
$optional = new Constraints\Optional([
new Constraints\Type('array'),
]);
$constraint = new Constraints\Collection([
'frames' => new Constraints\Collection([
'header' => $optional,
'content' => $optional,
]),
]);
但这并不能验证密钥是否存在。