0

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?

2
  • Variables don't match is this a typo: $responseMail and $responseEmail? Commented Nov 1, 2012 at 18:01
  • fixed thanks, but still problem is the same. Commented Nov 2, 2012 at 7:16

1 Answer 1

3

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);
        ...
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah you are right. Just a reminder for anyone who is still using 2.0 - for 2.0 use my code as the part of the answer is using 2.1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.