【问题标题】:Symfony 3: Call default validator inside a Custom Validator and check it the field is validatedSymfony 3:在自定义验证器中调用默认验证器并检查该字段是否已验证
【发布时间】:2016-07-18 10:50:33
【问题描述】:

我有一个自定义验证器,我在其中获取实体中定义的字段之一的值,然后我想使用内置验证器(例如 NotBlank())验证该字段,以便在验证后我如果该字段已验证,则为“true”,否则为“false”。

我的自定义验证器如下所示:

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\ConstraintValidator;


class UpdatePasswordValidator extends ConstraintValidator
{

    public function __construct()
    {

    }

    public function validate($email, Constraint $constraint)
    {
        /**
         * Getting field value from entity
         */
        $busNumber = $this->context->getRoot()->getData()->getBusnumber();

        /**
         * Validate $busNumber
         */
        $busNumberToValidate = $this->context->getValidator()
            ->inContext($this->context)
            ->atPath("busnumber")
            ->validate($busNumber, new NotBlank())->getViolations();
    }
}

在这种情况下,我想使用 NotBlank() 验证 $busNumber。 调用 getViolations() 会给我一个包含所有违规的对象,而我只需要一个与 $busNumber 验证相关联的对象。

更新:我真正想要实现的是:

if ($busNumberToValidate)
{
    echo "busNumber field is validated";
}
else
{
    echo "busNumber field is NOT validated";    
}

$busNumberToValidate 是否应包含或不包含“busNumber”字段的错误,具体取决于验证结果。

【问题讨论】:

    标签: symfony


    【解决方案1】:

    解决办法如下:

    $busNumberToValidate = $this->context->getValidator()->validate($busNumber, new NotBlank());
    
    if ($busNumberToValidate->has(0))
    {
      echo "field is not validated";
    }
    else
    {
      echo "field is validated";
    }
    
    // if you want to get the error message for the validated field 
    echo $busNumberToValidate->get(0)->getMessage();
    

    【讨论】:

      【解决方案2】:

      扩展Composite Constraint

      你可以在All Constraint找到例子

      【讨论】:

      • 谢谢,但这不是我想要实现的。所以我想知道是否可以使用 if 语句来检查验证字段是否有错误。我已经在更新中解释过了。
      猜你喜欢
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多