2016-03-11 71 views
1

我正在使用symfony2验证程序来验证表单和API POST请求。在验证程序中使用约束

我已经作出了验证这样的:

public function validate($content, Constraint $constraint) 
{ 
    if (in_array($constraint->type, self::DNS_TYPE, true) === false) { 
     $this->context->buildViolation('This DNS type is not valid.') 
      ->atPath($constraint->type) 
      ->addViolation(); 
    } 

    switch ($constraint->type) { 
     case 'A': 
      $contentConstraint = new Assert\Ip(['version' => '4']); 
      break; 
     case 'AAAA': 
      $contentConstraint = new Assert\Ip(['version' => '6']); 
      break; 
     case 'CNAME': 
     case 'NS': 
     case 'MX': 
      $contentConstraint = new Assert\Regex(['pattern' => '/^[[:alnum:]-\._]+$/u']); 
      break; 
     default: 
      $contentConstraint = false; 
      break; 
    } 

    // This part don't work 
    if ($this->validate('1.1.1.1', $contentConstraint)) { 
     $this->context->buildViolation('his value is not correct.') 
      ->atPath($content) 
      ->addViolation(); 
    } 
} 

第一个回调,并与我的表单开关的工作,但在使用第二个回调,symfony会返回一个错误

选项“类型“在约束中不存在Symfony \ Component \ Validator \ Constraints \ Ip

我不明白我的约束有什么问题。 为什么这个错误说我的IP约束没有type选项?

我该如何解决这个问题? 我也许不能在验证器中使用ip约束?

感谢

回答

1

约束http://api.symfony.com/2.3/Symfony/Component/Validator/Constraints/Ip.html没有type财产。 如果你需要它,你应该延长Symfony\Component\Validator\Constraints\Ip

+0

我不需要这个属性,我甚至不知道这个属性来自哪里。当我在另一个班级使用这个功能时,这个工作很好。我不明白为什么只有在这个班上我有这个错误 –