Symfony2自定义验证器

Bog*_*min 0 validation symfony

我正在尝试使用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. 
Run Code Online (Sandbox Code Playgroud)

重新加载后,错误消失,验证仍然不会触发,并返回代码有效.

这是相关代码:

//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 }
Run Code Online (Sandbox Code Playgroud)

无法想出这一个:(

小智 6

假设您的自定义验证器约束不在Symfony\Component\Validator\Constraints命名空间中,而是您自己的命名空间:NMSP\MyBundle\Validator.

您应该添加以下用法语句:

use NMSP\MyBundle\Validator as NMSPAssert;
Run Code Online (Sandbox Code Playgroud)

然后在$username属性上使用以下注释:

@NMSPAssert\Password()
Run Code Online (Sandbox Code Playgroud)

应该这样做.