Reputation: 41
I am trying to create my own service with a custom constraint and its validator.
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use AppBundle\Validator\AntiBadMail;
/**
* MailAlert
*
* @ORM\Table(name="mail_alert")
* @ORM\Entity(repositoryClass="AppBundle\Repository\MailAlertRepository")
* @UniqueEntity(fields="mail", message="Cette adresse a déjà été enregistrée.")
*/
class MailAlert
{
/**
* @var string
*
* @ORM\Column(name="Mail", type="string", length=255)
* @Assert\Email
* @AntiBadMail()
*/
private $mail;
}
namespace AppBundle\Validator;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class AntiBadMail extends Constraint
{
public function validatedBy()
{
return 'app.validator_antibadmail'; // Ici, on fait appel au service
}
}
namespace AppBundle\Validator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class AntiBadMailValidator extends ConstraintValidator
{
private $requestStack;
private $em;
public function __construct(RequestStack $requestStack, EntityManagerInterface $em)
{
$this->requestStack = $requestStack;
$this->em = $em;
}
public function validate($value, Constraint $constraint)
{
$request = $this->requestStack->getCurrentRequest();
$mail = $request->request->all()['form']['mail'];
$listPiecesOfMail = explode("@", $mail);
$mailBefore = $listPiecesOfMail[0];
$mailAfter = $listPiecesOfMail[1];
$ListAcceptedMails = $this->container->getParameters('listAcceptedMails');
if(count($mailBefore)<3){
$this->context->addViolation($constraint->messageBefore);
}
if(!preg_match('#'.implode('|',$ListAcceptedMails).'#', $mailAfter)){
$this->context->addViolation($constraint->messageAfter);
}
}
}
app.validator_antibadmail:
class: AppBundle\Validator\AntiBadMailValidator
arguments:
- "@request_stack"
- "@doctrine.orm.entity_manager"
I don't know why but I get the error than my validator doesn't exist. I use the validatedBy()
, and give it the proper name.
I am lost. Can you help me ?
EDIT : This is the error :
Constraint validator "app.validator_antibadmail" does not exist or it is not enabled. Check the "validatedBy" method in your constraint class "AppBundle\Validator\AntiBadMail".
Upvotes: 3
Views: 2198
Reputation: 287
For anyone still facing this issue, this is how you configure your Validator service with Symfony 3.4:
AppBundle\Validator\Constraints\CustomValidator:
public: true
class: AppBundle\Validator\Constraints\CustomValidator
autowire: true
tags: [{ name: validator.constraint_validator, alias: app.validator.custom }]
Everything else should be done as described in the question.
Upvotes: 2