Gab*_*dez 5 php symfony symfony-2.3
我正在创建一个自定义验证器约束来验证“联系人”,类似于“John Doe <jdoe@example.com>”。按照食谱,我创建了约束类:
<?php
namespace MyCompany\MyBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class Contact extends Constraint
{
public $message = 'The string "%string%" is not a valid Contact.';
}
Run Code Online (Sandbox Code Playgroud)
并创建了验证器:
<?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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
关键是我试图在我的自定义验证器中使用 Symfony 的 EmailValidator 来检查电子邮件是否有效。我不想重新发明轮子并使用我自己的正则表达式验证电子邮件。
尝试验证有效联系人时一切正常,但是,使用无效电子邮件(“Gabriel Garcia <infoinv4l1d3mai1.com>”)测试联系人时,它会因 PHP 致命错误而崩溃:
致命错误:在第 58 行的 /home/dev/myproject/vendor/symfony/symfony/src/Symfony/Component/Validator/Constraints/EmailValidator.php 中的非对象上调用成员函数 addViolation()
深入研究 EmailValidator.php 类,我意识到问题与 $context (ExecutionContext) 有关。这是 EmailValidator.php 的第 58 行:
$this->context->addViolation($constraint->message, array('{{ value }}' => $value));
Run Code Online (Sandbox Code Playgroud)
似乎该类的上下文属性为空。有谁知道为什么?我需要在某处注射吗?
提前致谢。
PS:我使用的是 Symfony 2.3。不要关注正则表达式,我知道它可以好得多。现在只是为了测试。
小智 5
我认为最初的问题是关于在自定义验证器中使用 EmailValidator 并且在这种情况下容器不可用,所以
$this->get('validator');
Run Code Online (Sandbox Code Playgroud)
不管用。似乎海报唯一的问题是将 EmailValidator addViolation 添加到正确的上下文中。这应该有效:
$emailValidator = new EmailValidator();
$emailValidator->initialize($this->context);
$emailValidator->validate($matches[2], $constraint);
Run Code Online (Sandbox Code Playgroud)
可以直接使用约束
请参阅http://symfony.com/doc/current/book/validation.html
use Symfony\Component\Validator\Constraints\Email
$emailConstraint = new Email();
// use the validator to validate the value
$errorList = $this->get('validator')->validateValue(
$email,
$emailConstraint
);
Run Code Online (Sandbox Code Playgroud)
最良好的问候
| 归档时间: |
|
| 查看次数: |
4496 次 |
| 最近记录: |