0

我想使用 symfony2 验证器组件对字符串进行简单验证。(这需要在 symfony 2.0 中)

$responseEmail = 'somestring';

$validator = new Validator(
    new ClassMetadataFactory(new StaticMethodLoader()),
    new ConstraintValidatorFactory()
);

$constraint = new Assert\Collection(array(
    'responseEmail' => new Assert\Collection(array(
        new Assert\Email(),
        new Assert\NotNull(),
    )),
));

$violations = $validator->validateValue(array('responseEmail' => $responseEmail), $constraint);

这给了我一个错误:

Expected argument of type array or Traversable and ArrayAccess, string given

有谁知道为什么?

4

1 回答 1

3

目前您告诉该$constraintresponseEmail 是一个数组。

试试这个:

use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert;
...
class ...
{
    public function validationAction()
    {
        $validator = Validation::createValidator();
        $responseEmail = 'somestring';
        $constraint = new Assert\Collection(array(
            'responseEmail' => array(new Assert\Email(), new Assert\NotNull()),
        ));

        $violations = $validator->validateValue(array('responseEmail' => $responseEmail), $constraint);
        ...
    }
}
于 2012-11-01T18:06:00.133 回答