Reputation: 33
I have some $customObject which is an instance of CustomClass and I want to validate it with Symfony Validation. CustomClass is not a Doctrine Entity Class.
Here is my CustomClass:
use Symfony\Component\Validator\Constraints as Assert;
class SomeClass {
/**
* @Assert\NotBlank(message="Status should not be empty")
* @Assert\Choices({"200", "201"})
*/
protected $status;
/**
* @Assert\Type("string")
* @Assert\NotBlank(message="Content should not be empty")
*/
protected $content;
}
Trying to validate it:
$constraints = Validation::createValidator()->validate($customObject);
But constraints count is always 0 even if object is invalid, seems like annotation parser ignores this object annotations. Working well on Doctrine entities in the same project. Any ideas?
Upvotes: 1
Views: 1369
Reputation: 88
You need to get the Validator service :
without autowiring
$validator = $this->get('validator');
with autowiring
use Symfony\Component\Validator\Validator\ValidatorInterface;
...
public function myMethod(ValidatorInterface $validator)
And then
$errors = $validator->validate($customObject);
Do you have in your config :
framework:
validation: { enable_annotations: true }
See more info here : https://symfony.com/doc/current/validation.html#using-the-validator-service
Upvotes: 3