doutao6380 2014-07-16 19:55
浏览 46
已采纳

Symfony实体验证不会报告违规行为

I am trying to add some validation to my entity, using the Symfony validation component, i have added some constraints to my User Entity.

/**
 * @param ClassMetadata $metadata
 */
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
    $metadata->addPropertyConstraint('username', new Assert\NotBlank);
    $metadata->addPropertyConstraint('password', new Assert\NotBlank);
    $metadata->addPropertyConstraint('first_name', new Assert\NotBlank);
    $metadata->addPropertyConstraint('last_name', new Assert\NotBlank);
}

Now i want to test if i get some errors, when violating the constraints, this is done like this.

    $user = new User();
    $user->username = '';
    $user->password = '';

    $validator = Validation::createValidator();

    if (0 < count($validator->validate($user))) {
        throw new \RuntimeException('The given user is invalid');
    }

But the count is zero, which is odd, as all the constraints is clearly violated? Am i missing something here? Well i must be :D.

Might be worth to notice, that my application is not a Symfony application; it's a ordinary php application, i am just using the component.

  • 写回答

1条回答 默认 最新

  • doujing2497 2014-07-16 22:10
    关注

    You need to specify which methods act as mapping methods:

    $validator = Validation::createValidatorBuilder()
        ->addMethodMapping('loadValidatorMetadata')
        ->getValidator()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码