【问题标题】:Custom constraint not show message自定义约束不显示消息
【发布时间】:2013-12-28 21:02:04
【问题描述】:

this 线程中,我正在与自定义验证器进行斗争。感谢 stackoverflow 用户,我可以使用验证器。现在,我不能这样做显示错误。 验证器类是:

class ExistEmailValidator extends ConstraintValidator
{

    protected $userService;

    public function setUserService($us) {
        $this->userService = $us;
    }

    public function validate($value, Constraint $constraint)
    {
        if($this->userService->existUserEmail($value) == false){
            $this->context->addViolation($constraint->message, array('%string%' => $value));
        }

    }

    public function getTargets(){
        return self::CLASS_CONSTRAINT;
    }

}

我在树枝上写了form_errors(myForm),但没有显示错误。验证器工作正常,但没有设置错误。

有什么想法吗?

【问题讨论】:

标签: symfony custom-validators


【解决方案1】:

请参阅Class Constraint 文档。类约束被传递给一个对象而不是一个简单的值。您是否在实体上设置了正确的注释?例如,

use My\Namespace\Validator\Constraints as MyAssertions;

/**
 * @MyAssertions\ExistEmailValidator
 *
 */
class MyEntity
{
    protected $id;

    protected $email;

    // etc...

}

在您的验证器中,您将收到一个 MyEntity 实例,您可以从中检索电子邮件值并对其进行验证。正如上面评论中提到的,您可能还想使用 addViolationAt。

我希望这会有所帮助,并且我正确理解了您的情况。我敢肯定那里有更好的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 2019-09-22
    • 2016-10-13
    • 1970-01-01
    相关资源
    最近更新 更多