Martyn
Martyn

Reputation: 6383

Symfony validation not returning any violations for NotBlank

I'm using Symfony validation within my own app (not Symfony). I'm expecting it to return violations as I haven't populated the Id property:

$user = new User();
$user->setId('');
//...

$validator = \Symfony\Component\Validator\Validation::createValidator();
$errors = $validator->validate($user);
var_dump(count($errors)); exit; // outputs: 0

However, validate returns no violations.

Here is my User class with constraint annotations:

use Symfony\Component\Validator\Constraints as Assert;

class User {

    /**
     * @Assert\NotBlank
     */
    private $id;

    //...

    public function getId(): string {
        return $this->id;
    }

    public function setId(string $id): void {
        $this->id = $id;
    }

    //...

Where am I going wrong? According to the docs, a blank string should trigger a violation for this constraint - https://symfony.com/doc/current/reference/constraints/NotBlank.html

Upvotes: 0

Views: 895

Answers (2)

Arno van Oordt
Arno van Oordt

Reputation: 3520

I ran into the same problem. For some reason the standalone version of the component doesn't have the ability to check entities. I ended up making a function that reflects the entity class you give it and calls the validate function for each property with an contraint atrribute in the entity. It's probably not as advanced as the original Symfony version but for simple entities it gets the job done. You can find the code here: https://stackoverflow.com/a/78641601/1572330

Upvotes: 0

shaax
shaax

Reputation: 336

You don't need Annotations if you use Validation. Try this :

$validator = Validation::createValidator();
$violations = $validator->validate($user->getId, [
    new NotBlank(),
]);

Upvotes: 0

Related Questions