I create a special validator constraint to check for "contact", something like "John Doe < jdoe@example.com >". Following the Cookbook , I created the Constraint class:
<?php namespace MyCompany\MyBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; class Contact extends Constraint { public $message = 'The string "%string%" is not a valid Contact.'; }
and also created a validator:
<?php namespace MyCompany\MyBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Constraints\Email; use Symfony\Component\Validator\Constraints\EmailValidator; class ContactValidator extends ConstraintValidator { public function validate($value, Constraint $constraint) { if (!preg_match('#(.*)\s+<(.*)>#', $value, $matches)) { $this->context->addViolation($constraint->message, array('%string%' => $value)); } $emailValidator = new EmailValidator(); if (isset($matches[2]) && $emailValidator->validate($matches[2], new Email())) { $this->context->addViolation($constraint->message, array('%string%' => $value)); } } }
The fact is that I'm trying to use Symfony EmailValidator inside my custom validator to verify that the email is valid. I do not want to reinvent the wheel and check emails using my own regular expression.
Everything is fine when trying to confirm a valid contact, but checking the contact with an invalid email address ("Gabriel Garcia <infoinv4l1d3mai1.com>"), it fails with a PHP Fatal error:
Fatal error: call addViolation () member function for non-object in /home/dev/myproject/vendor/symfony/symfony/src/Symfony/Component/Validator/Constraints/EmailValidator.php on line 58
Delving into the EmailValidator.php class, I realized that the problem was with $ context (ExecutionContext). Here is line 58 of EmailValidator.php:
$this->context->addViolation($constraint->message, array('{{ value }}' => $value));
It seems that the class context attribute is null. Does anyone know why? Do I need to enter something?
Thanks in advance.
PS: I am using Symfony 2.3. Ignore the regex, I know it can be much better. It is just for testing right now.