在Symfony2中使用Regex字符串约束而不是自定义约束

时间:2013-06-17 07:27:01

标签: symfony constraints validation symfony-2.3

我已按照Symfony2食谱中this recipe中的步骤创建了自定义电话限制。

约束类:

namespace Foo\Bundle\StackBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class Phone extends Constraint
{
  public $message = 'The Phone contains an illegal character';
}

验证员类:

namespace Foo\Bundle\StackBundle\Validator\Constraints;

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

    /**
     * @Annotation
     */
    class PhoneValidator extends ConstraintValidator
    {
      public function validate($value, Constraint $constraint)
      {
        $length = strlen($value);

        if (is_null($value)) {
          return;
        }

        if ( $length > 14 || ! preg_match("/\([1-9]{2}\) [0-9]{4}-[0-9]{4}/", $value)) {
          $this->context->addViolation($constraint->message, array(), $value);
        }
      }
    }

此验证器工作正常,但我想使用Symfony2提供的Regex string constraint

我试图在约束类中实现它:

namespace Foo\Bundle\StackBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @Annotation
 */
class Phone extends Constraint
{

  public $message = 'The Phone contains an illegal character';
  public static function loadValidatorMetadata(ClassMetadata $metadata)
  {
    $metadata->addPropertyConstraint('description', new Assert\Regex(array(
      'pattern' => '/\([1-9]{2}\) [0-9]{4}-[0-9]{4}/'
    )));
  }
}

但它给我一个致命的错误,要求我实现验证方法:

  

致命错误:类   Foo \ Bundle \ StackBundle \ Validator \ Constraints \ CepValidator包含   1抽象方法因此必须声明为抽象或实现   其余的方法   (Symfony的\元器件\验证\ ConstraintValidatorInterface ::验证)

但是validate方法已经在ConstraintValidator类中实现了(尽管如果实现得当,我认为loadValidatorMetadata中指示的模式应该足够了。)

有关如何实现这一目标的任何建议?

更新

似乎所有工作正常,为了使Regex约束起作用,在约束类中设置模式后,validate方法可以在验证器类中声明为空,如下所示:

namespace Foo\Bundle\StackBundle\Validator\Constraints;

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

/**
 * @Annotation
 */
class PhoneValidator extends ConstraintValidator
{
  public function validate($value, Constraint $constraint)
  {   
  }
}

1 个答案:

答案 0 :(得分:2)

CepValidator 会引发错误,而不是PhoneValidator。

你有另一个档案......

src/Foo/Bundle/StackBundle/Validator/Constraints/CepValidator.php

...缺少validate()方法。