我收到此错误:
消息:“[语义错误]注释 属性中的“@Symfony \ Component \ Validator \ Constraints \ Length” User :: $ name不存在,或者无法自动加载。“
这是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);
如何解决此问题?
答案 0 :(得分:5)
Doctrine不使用自动加载PHP,您必须使用autoloadRegistry注册:
AnnotationRegistry::registerAutoloadNamespace("Symfony\Component\Validator\Constraint", "path/to/symfony/library/validator");
答案 1 :(得分:4)
将Symfony \ Component \ Validator \ Constraints用作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;
答案 2 :(得分:0)
在Symfony 2.1中添加了长度约束,因此如果您使用的是Symfony 2.0,则无法使用它。
答案 3 :(得分:0)
PHP和Doctrine注释中存在一个错误,有时会被use
包含混淆。您必须在类声明中添加PHPDoc注释,此错误将消失。
答案 4 :(得分:0)
如果您将symfony / validator作为独立使用,则必须手动注册验证器的命名空间
$loader = require 'vendor/autoload.php';
AnnotationRegistry::registerLoader([$loader, 'loadClass']);
答案 5 :(得分:0)
使用作曲家,而不是手动注册验证者的名称空间,您可以做
composer require validator