Reference / Symfony
/

Validation

Constraint-based validation that runs against any object — entities, DTOs, scalars — independent of the form system.

Foundational
  • Add constraints via attributes on entity properties (`#[Assert\NotBlank]`, `#[Assert\Email]`, etc.) or in YAML.
  • Inject `ValidatorInterface` and call `$validator->validate($object)` to validate anywhere — controllers, services, commands.
  • Forms call validation automatically when you call `isValid()`.
  • Validation groups let you apply different rules in different contexts (e.g. registration vs. profile edit).
  • Custom constraints: define a Constraint + ConstraintValidator pair for non-trivial rules.
class CreateUser
{
    #[Assert\Email]
    public string $email;

    #[Assert\Length(min: 12)]
    public string $password;
}

$errors = $validator->validate($dto);
if (count($errors) > 0) { /* handle */ }

Common gotchas

  • Validation runs against the model, not the request. If a transformer fails before validation, you get a transformation error instead of a constraint violation.
  • Groups default to `['Default']`. If you set `validation_groups` on a form, only those run — easy to forget and ship unvalidated data.