php - 从未检查过的自定义约束

标签 php validation symfony

我正在尝试用他的约束做一个简单的验证器。

约束

namespace Me\MyBundle\Validator\Constraint;

use Symfony\Component\Validator\Constraint;

class MyConstraint extends Constraint
{
    public $message = 'Grossière erreur';
}

验证器

namespace Me\MyBundle\Validator\Constraint;

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

class MyConstraintValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $this->context->buildViolation($constraint->message)
            ->addViolation();
        return false;
    }
}

验证

Me\MyBundle\Entity\MyEntity:
    properties:
        myField:
            - Length:
                min: 9
            - Me\MyBundle\Validator\Constraint\MyConstraint: ~

如您所见,myField 有 2 个约束条件,Length 被检查但 MyConstraint 从未被检查。

有什么问题吗?我该如何调试它?

(交响乐 2.5.9)

最佳答案

调试提示:

在您的 Controller 中,使用以下命令获取您的属性的所有约束。

$factory          = $this->container->get('validator.mapping.class_metadata_factory');
$classMetadata    = $factory->getMetadataFor('Your\Bundle\Entity\Name');
$propertyMetadata = $classMetadata->getPropertyMetadata('propertyName');

( inspired by this answer )

如果您在 $propertyMetadata 中看到这两个约束,那么 Length 可能会干扰自定义约束,因此请尝试在没有 Length 约束的情况下运行代码。

关于php - 从未检查过的自定义约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29261512/

相关文章:

php - 使用 Knp Snappy 生成 pdf 文件时出现错误字符

php - 从 mysql 更改为 mysqli

php - AsyncTask 连接超时

PHP MySQL : Proper/easier way to implement dynamic filtering

在 "index"的情况下,PHP $_GET 无法获取 RewriteRule 的值

asp.net - 在局部 View 中强制使用无 Html.BeginForm/Ajax.BeginForm 的无障碍语法

php - 如何使服务像 SwiftMailer 一样在 kernel.terminate 上工作?

android - 在 alertDialog 中验证 EditText

c# - 验证,在多个控件上显示数据错误

php - 使用 YAML 的 Symfony2 Doctrine 索引