How to Handle Different Error Levels

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:

  1. Apply different error levels to the validation constraints;
  2. 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:

  • Annotations

    1. // src/Entity/User.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class User
    5. {
    6. /**
    7. * @Assert\NotBlank(payload={"severity"="error"})
    8. */
    9. protected $username;
    10. /**
    11. * @Assert\NotBlank(payload={"severity"="error"})
    12. */
    13. protected $password;
    14. /**
    15. * @Assert\Iban(payload={"severity"="warning"})
    16. */
    17. protected $bankAccountNumber;
    18. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\User:
    3. properties:
    4. username:
    5. - NotBlank:
    6. payload:
    7. severity: error
    8. password:
    9. - NotBlank:
    10. payload:
    11. severity: error
    12. bankAccountNumber:
    13. - Iban:
    14. payload:
    15. severity: warning
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\User">
    7. <property name="username">
    8. <constraint name="NotBlank">
    9. <option name="payload">
    10. <value key="severity">error</value>
    11. </option>
    12. </constraint>
    13. </property>
    14. <property name="password">
    15. <constraint name="NotBlank">
    16. <option name="payload">
    17. <value key="severity">error</value>
    18. </option>
    19. </constraint>
    20. </property>
    21. <property name="bankAccountNumber">
    22. <constraint name="Iban">
    23. <option name="payload">
    24. <value key="severity">warning</value>
    25. </option>
    26. </constraint>
    27. </property>
    28. </class>
    29. </constraint-mapping>
  • PHP

    1. // src/Entity/User.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class User
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addPropertyConstraint('username', new Assert\NotBlank([
    10. 'payload' => ['severity' => 'error'],
    11. ]));
    12. $metadata->addPropertyConstraint('password', new Assert\NotBlank([
    13. 'payload' => ['severity' => 'error'],
    14. ]));
    15. $metadata->addPropertyConstraint('bankAccountNumber', new Assert\Iban([
    16. 'payload' => ['severity' => 'warning'],
    17. ]));
    18. }
    19. }

2. Customize the Error Message Template

When validation of the User object fails, you can retrieve the constraint that caused a particular failure using the [getConstraint()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Validator/ConstraintViolation.php "Symfony\Component\Validator\ConstraintViolation::getConstraint()") method. Each constraint exposes the attached payload as a public property:

  1. // a constraint validation failure, instance of
  2. // Symfony\Component\Validator\ConstraintViolation
  3. $constraintViolation = ...;
  4. $constraint = $constraintViolation->getConstraint();
  5. $severity = $constraint->payload['severity'] ?? null;

For example, you can leverage this to customize the form_errors block so that the severity is added as an additional HTML class:

  1. {%- block form_errors -%}
  2. {%- if errors|length > 0 -%}
  3. <ul>
  4. {%- for error in errors -%}
  5. <li class="{{ error.cause.constraint.payload.severity ?? '' }}">{{ error.message }}</li>
  6. {%- endfor -%}
  7. </ul>
  8. {%- endif -%}
  9. {%- endblock form_errors -%}

See also

For more information on customizing form rendering, see How to Customize Form Rendering.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.