6

I get this error:

Message: "[Semantical Error] The annotation "@Symfony\Component\Validator\Constraints\Length" in property User::$name does not exist, or could not be auto-loaded."

This is the code on Github https://github.com/symfony/Validator

use Symfony\Component\Validator\Validation; 
use Symfony\Component\Validator\Constraints as Assert;

class User {
    /**
     * @Assert\Length(min = 3)
     * @Assert\NotBlank
     */
    private $name;

    /**
     * @Assert\Email
     * @Assert\NotBlank
     */
    private $email;

    public function __construct($name, $email)
    {
        $this->name = $name;
        $this->email = $email;
    }

    /**
     * @Assert\True(message = "The user should have a Google Mail account")
     */
    public function isGmailUser()
    {
        return false !== strpos($this->email, '@gmail.com');
    } 
}

$validator = Validation::createValidatorBuilder()
    ->enableAnnotationMapping()
    ->getValidator();

$user = new User('John Doe', 'john@example.com');

$violations = $validator->validate($user);

How can I fix this problem ?

4

6 回答 6

5

Doctrine 不使用自动加载 PHP ,您必须使用 autoloadRegistry 注册:

AnnotationRegistry::registerAutoloadNamespace("Symfony\Component\Validator\Constraint", "path/to/symfony/library/validator");
于 2012-09-18T04:21:06.410 回答
5

使用 Symfony\Component\Validator\Constraints 作为断言;

    /**
     * @var float $weight
     *
     * @ORM\Column(name="weight", type="decimal",precision=3,scale=2, nullable=true)
     * 
     * @Assert\Range(
     *      min = "90",
     *      max = "350",
     *      minMessage = "You must weight at least 90",
     *      maxMessage = "You cannot weight more than 300"


     * )

     * @Assert\NotBlank(groups={"group one","goup 2"}) 
     * @Assert\Regex(pattern= "/[0-9]/",message="Require number only") 
     */
    private $weight=0;
于 2013-04-03T18:25:49.733 回答
0

PHP 和 Doctrine 注释中有一个错误,有时它会被use包含混淆。你必须在你的类声明中添加一个 PHPDoc 注释,这个错误就会消失。

于 2014-09-04T15:30:40.287 回答
0

长度约束是在 Symfony 2.1 中添加的,因此如果您使用 Symfony 2.0,您将无法使用它。

请参阅Length 约束的文档

于 2012-10-28T10:01:30.383 回答
0

使用作曲家,而不是手动注册验证器的命名空间,你可以这样做

composer require validator

于 2019-01-18T11:16:27.077 回答
0

如果你使用 symfony/validator 作为独立的,你必须手动注册验证器的命名空间

$loader = require 'vendor/autoload.php';
AnnotationRegistry::registerLoader([$loader, 'loadClass']);
于 2018-05-04T09:20:00.157 回答