我正在尝试使用自定义约束及其验证器创建自己的服务。
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"
我不知道为什么但是我得到错误而不是我的验证器不存在。我使用validatedBy()
,并给它正确的名称。
我迷路了。你能帮助我吗 ?
编辑:这是错误:
约束验证程序“app.validator_antibadmail”不存在或未启用。检查约束类“AppBundle \ Validator \ AntiBadMail”中的“validatedBy”方法。
答案 0 :(得分:0)
起来!我使用@Asserts / Email完成,但如果有人有想法,我准备好了!
答案 1 :(得分:0)
对于仍然面临此问题的任何人,这是使用Symfony 3.4配置Validator服务的方式:
AppBundle\Validator\Constraints\CustomValidator:
public: true
class: AppBundle\Validator\Constraints\CustomValidator
autowire: true
tags: [{ name: validator.constraint_validator, alias: app.validator.custom }]
其他所有操作都应按照问题中的说明进行。