Validation

Assert constraints

Constraints are small attribute rules placed above entity properties. NotBlank rejects empty strings, and Length sets the shortest and longest allowed values.

Each rule carries a default message, so broken input explains itself. Start with two or three rules per field and grow the list with real feedback.

#[Assert\NotBlank] #[Assert\Length(min: 3, max: 255)] private string $name = "";

Forms validate

Forms run the validator for you: isValid checks every constraint on the bound object. No extra service calls are needed inside form actions.

That is why invalid forms re-render instead of saving. The error list travels with the form view into the template.

if ($form->isSubmitted() && $form->isValid()) { echo "All constraints passed"; }

Validate manually

Console commands and API actions have no form, so they call the validator directly. The validate method returns a list of violations, empty when the object is clean.

Loop the list or read the first item during debugging. Each violation knows its message and the field that broke the rule.

$violations = $validator->validate($product); if (count($violations) > 0) { echo $violations[0]->getMessage(); }

Custom messages

Default messages are clear, but products need their own voice. Every constraint accepts a message option with plain words for visitors.

Write messages for humans, not developers. Name the expected value instead of the rule name, and keep each message to one short sentence.

#[Assert\NotBlank(message: "Name must not stay empty")] #[Assert\Length(min: 3, max: 255, maxMessage: "Name is too long")]

Next: Services and DI

Article author: Arthur Isaev