.. index::
single: Validation; Error Levels
single: Validation; Payload
How to Handle Different Error Levels
====================================
Sometimes, you may want to display constraint validation error messages differently
based on some rules. For example, you have a registration form for new users
where they enter some personal information and choose their authentication
credentials. They would have to choose a username and a secure password,
but providing bank account information would be optional. Nonetheless, you
want to make sure that these optional fields, if entered, are still valid,
but display their errors differently.
The process to achieve this behavior consists of two steps:
#. Apply different error levels to the validation constraints;
#. Customize your error messages depending on the configured error level.
1. Assigning the Error Level
----------------------------
Use the ``payload`` option to configure the error level for each constraint:
.. configuration-block::
.. code-block:: php-annotations
// src/Entity/User.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class User
{
/**
* @Assert\NotBlank(payload={"severity"="error"})
*/
protected $username;
/**
* @Assert\NotBlank(payload={"severity"="error"})
*/
protected $password;
/**
* @Assert\Iban(payload={"severity"="warning"})
*/
protected $bankAccountNumber;
}
.. code-block:: yaml
# config/validator/validation.yaml
App\Entity\User:
properties:
username:
- NotBlank:
payload:
severity: error
password:
- NotBlank:
payload:
severity: error
bankAccountNumber:
- Iban:
payload:
severity: warning
.. code-block:: xml