Change record status: 
Project: 
Introduced in branch: 
8.x
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

  1. 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."
  2. 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 &quot;&quot; — two double quotes without any content).'),
      '#default_value' => $alt,
      '#maxlength' => 2048,
    );
Impacts: 
Module developers
Themers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done