Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By pillarsdotnet on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.x
Issue links:
Description:
Problem/Motivation
Accessibility guidelines recommend specific, meaningful error messages when required form elements are empty. However, FAPI currently does not support custom error messages for required elements.
Proposed resolution
- Support a
#required_error
property for form elements. If set, this message will be used when a required form element is empty, instead of the default "Field x is required." - Additionally set a
#required_but_empty
flag automatically during validation when the required field is empty. This is an internal property and is not set manually. It allows #element_validate handlers to set a custom required error message, but without having to re-implement the complex logic to figure out whether the field value is empty.
Usage
Used in /core/modules/editor/src/Form/EditorImageDialog.php - buildForm()
$form['attributes']['alt'] = array(
'#title' => $this->t('Alternative text'),
'#placeholder' => $this->t('Short description for the visually impaired'),
'#type' => 'textfield',
'#required' => TRUE,
'#required_error' => $this->t('Alternative text is required.<br><em>(Only in rare cases should this be left empty. To create empty alternative text, enter ""
— two double quotes without any content).'),
'#default_value' => $alt,
'#maxlength' => 2048,
);
Impacts:
Module developers
Themers