我正在使用Validator Component来验证数组。
我的验证是条件,所以我创建了组。
但我无法正常工作。当检查约束时,验证器会忽略这些组。
这是我的(单位)测试:
public function testValidator()
{
$book = array(
'title' => 'My Book',
'author' => array(
'first_name' => 'Fabien',
'last_name' => 'Potencier',
),
);
$constraint = new Assert\Collection(array(
'groups' => array('MyGroup'),
'fields' => array(
'title' => new Assert\Length(array('min' => 10, 'groups' => 'MyGroup')),
'author' => new Assert\Collection(array(
'groups' => array('MyGroup'),
'fields' => array(
'first_name' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 10))),
'last_name' => new Assert\Length(array('min' => 10, 'groups' => 'MyGroup')),
)
)),
)
));
// $this->v is the validator service
$errors = $this->v->validateValue($book, $constraint, null, array('MyGroup'));
$this->assertEquals(1, $errors->count(), $errors);
}
结果是:
PHPUnit 3.7.14 by Sebastian Bergmann.
Configuration read from phpunit.xml
.F
Time: 0 seconds, Memory: 3.00Mb
There was 1 failure:
1) WebFactory\ValidationNormalizer\Tests\ValidationNormalizerTest::testValidator
[title]:
This value is too short. It should have 10 characters or more.
[author][first_name]:
This value is too short. It should have 10 characters or more.
[author][last_name]:
This value is too short. It should have 10 characters or more.
Failed asserting that 3 matches expected 1.
src/WebFactory/ValidationNormalizer/Tests/ValidationNormalizerTest.php:64
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
我只想验证MyGroup约束。
错误在哪里?
答案 0 :(得分:0)
您已将整个收藏集添加到“MyGroup”群组中。
'author' => new Assert\Collection(array(
'groups' => array('MyGroup'),
因此它验证了整个数组
'author' => array(
'first_name' => 'Fabien',
'last_name' => 'Potencier',
),
...如果您将验证组指定为“MyGroup”。这种行为是正确的。
如果您只想在使用验证组“MyGroup”时验证“title”和“lastname”,请使用:
$constraint = new Assert\Collection(array(
'fields' => array(
'title' => new Assert\Length(array('min' => 10, 'groups' => 'MyGroup')),
'author' => new Assert\Collection(array(
'fields' => array(
'first_name' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 10))),
'last_name' => new Assert\Length(array('min' => 10, 'groups' => 'MyGroup')),
)
)),
)
));