6
votes

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', '[email protected]');

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

How can I fix this problem ?

6

6 Answers

5
votes

Doctrine don't use autoload PHP , you must register with autoloadRegistry:

AnnotationRegistry::registerAutoloadNamespace("Symfony\Component\Validator\Constraint", "path/to/symfony/library/validator");
5
votes

use Symfony\Component\Validator\Constraints as Assert;

    /**
     * @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;
0
votes

The Length constraint was added in Symfony 2.1, so you won't be able to use it if you are using Symfony 2.0.

See the documentation for the Length constraint.

0
votes

There is a bug in PHP and Doctrine annotation and sometimes it gets confused by the use includes. You have to add a PHPDoc comment on your class declaration and this error will be gone.

0
votes

If you use symfony/validator as standalone you have to manually register the validator's namespace

$loader = require 'vendor/autoload.php';
AnnotationRegistry::registerLoader([$loader, 'loadClass']);
0
votes

Using composer, instead of manually registering the validator's namespace, you can just do

composer require validator