我正在尝试使用symfony2构建自定义验证器,但发生了一些奇怪的事情:
我已按照symfony2 cookbook中的步骤创建了Password和PasswordValidate,但第一次加载页面时出现此错误:
AnnotationException: [Semantical Error] The annotation "@Symfony\Component\Validator\Constraints\Password" in property NMSP\MyBundle\Entity\User::$password does not exist, or could not be auto-loaded.
重新加载后,错误消失,验证仍然没有触发,返回代码有效。
这是相关代码:
//annotation declaration:
/**
* @ORM\Column(type="string", length="32", unique="true")
*
* @Assert\MinLength(3)
* @Assert\Password2()
*/
protected $password;
//load files with the following in the code
services:
validator.password:
class: NMSP\MyBundle\Validator\PasswordValidator
tags:
- { name: validator.constraint_validator, alias: password }
无法解决这个问题:(
答案 0 :(得分:6)
假设您的自定义验证程序约束不在Symfony \ Component \ Validator \ Constraints命名空间中,而是您自己的命名空间:NMSP \ MyBundle \ Validator。
您应该添加以下用法声明:
use NMSP\MyBundle\Validator as NMSPAssert;
然后在$username
属性上使用以下注释:
@NMSPAssert\Password()
应该这样做。