Drupal - How to set multiple error messages with form_set_error?

I would change the code to issue a single call to form_set_error() per element:

$errors = array();
if (strpos($form_state["values"]["body"], "<h1") === true)
    $error_messages["body"][] = "Blalalabalbal bablalbabla.";

if (strpos($form_state["values"]["body"], "<h3") === false)
    $error_messages["body"][] = "Do this do that balbablalba.";

foreach ($error_messages as $element => $messages) {
    form_set_error($element, theme('item_list', array('items' => messages)));
}

I've created separate function for that:

function form_set_error_multiple($name = NULL, $messages = '', $limit_validation_errors = NULL) {
  return form_set_error('extra][items', implode('</li><li>', $messages));
}

And then I can call it like that:

$errors = [
  'My element error',
  'Another error for the same element',
]

form_set_error_multiple('my_element', $errors);

Tags:

Forms