TroodoN-Mike
TroodoN-Mike

Reputation: 16175

Symfony2 Validator Component on a string

I want to do simple validation on a string using symfony2 Validator Component. (This needs to be in 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);

This gives me an error:

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

Anyone knows why?

Upvotes: 0

Views: 991

Answers (1)

Mats Rietdijk
Mats Rietdijk

Reputation: 2576

At the moment your telling the $constraint that responseEmail is an array.

Try this:

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);
        ...
    }
}

Upvotes: 3

Related Questions