Drupal - How to use HTML tags in form error messages

All errors added to the form state will be finally handled by drupal_set_message.
That means that you can either use strings, or any class that implements the MarkupInterface.
Looking at that list I would say that what you are looking for is FormattableMarkup or even better TranslatableMarkup.

An example would then be:

$your_error = new TranslatableMarkup('<b>@message!</b>', array('@message' => 'A bold error'));
$form_state->setError($element, $your_error); 

Good luck!


The other answer does not allow HTML inside the @message, here is what worked for me.

  $message = '<b>A bold error</b>';
  $rendered_message = \Drupal\Core\Render\Markup::create($message);
  $error_message = new TranslatableMarkup ('@message', array('@message' => $rendered_message));
  $form_state->setErrorByName('field_name', $error_message);

Important: For security reasons, make sure that $message value is authored by an admin only; otherwise, you cannot use this answer!

Note: You have to declare the new dependency at top of your class.php file, or you will receive an error and WSOD in browser:

use \Drupal\Core\StringTranslation\TranslatableMarkup;

Tags:

8