Magento 2 Experten — Hyvä Theme, Tailwind CSS & SEO aus einer Hand ›

More Constraint Types and Custom Error Messages

More Constraint Types and Custom Error Messages

~14 Min. Lesezeit Zuletzt aktualisiert am August 8, 2026

A NEW priority field on Project demonstrates further constraint types – EXACTLY the same classes as in the Symfony course, here for the first time with CUSTOM, user-defined error messages.

Adding the priority field

api/src/Entity/Project.php
use Symfony\Component\Validator\Constraints as Assert;

// ... inside the class:

#[ORM\Column]
#[Assert\Range(
    min: 1,
    max: 5,
    notInRangeMessage: 'Priority must be between {{ min }} and {{ max }}.'
)]
private int $priority = 3;

public function getPriority(): int
{
    return $this->priority;
}

public function setPriority(int $priority): static
{
    $this->priority = $priority;

    return $this;
}

Achtung: {{ min }}/{{ max }} in the error message are Symfony Validator placeholders, NOT Magento template directives – inside PHP strings in the source code this is COMPLETELY unproblematic, the warning from the BLOG-REWRITE-ANLEITUNG only concerns HTML content fields, not PHP code.

Migration for the new field

docker compose exec php bin/console make:migration
docker compose exec php bin/console doctrine:migrations:migrate --no-interaction

Testing the custom message

curl -k -X POST https://localhost/api/projects \
  -H 'Content-Type: application/json' \
  -d '{"name": "Test", "priority": 9}'
{
  "violations": [
    {"propertyPath": "priority", "message": "Priority must be between 1 and 5."}
  ]
}

The CUSTOM message REPLACES API Platform's default English message – DECISIVE for a frontend whose UI should run entirely in German (or English, depending on the store), WITHOUT having to maintain Symfony's internal translation files.

More useful constraints at a glance

ConstraintChecks
#[Assert\Choice(choices: [...])]Value must come from a fixed list (e.g. status strings)
#[Assert\Positive]Number must be greater than zero
#[Assert\Email]Valid email address (important from block 6 for User)
#[Assert\Count(min: 1)]Collection (e.g. tags) must not be empty

Tipp: ALL Symfony Validator constraints work UNCHANGED in API Platform, since underneath it's EXACTLY the same symfony/validator component – the OFFICIAL Symfony documentation on constraints is therefore ALSO fully valid for API Platform.