3 namespace Drupal\Core\Render\Element;
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\Core\Render\Element;
9 * Provides a form input element for entering an email address.
12 * - #default_value: An RFC-compliant email address.
13 * - #size: The size of the input element in characters.
14 * - #pattern: A string for the native HTML5 pattern attribute.
18 * $form['email'] = array(
20 * '#title' => $this->t('Email'),
21 * '#pattern' => '*@example.com',
25 * @see \Drupal\Core\Render\Element\Render\Textfield
27 * @FormElement("email")
29 class Email extends FormElement {
32 * Defines the max length for an email address
34 * The maximum length of an email address is 254 characters. RFC 3696
35 * specifies a total length of 320 characters, but mentions that
36 * addresses longer than 256 characters are not normally useful. Erratum
37 * 1690 was then released which corrected this value to 254 characters.
38 * @see http://tools.ietf.org/html/rfc3696#section-3
39 * @see http://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690
41 const EMAIL_MAX_LENGTH = 254;
46 public function getInfo() {
47 $class = get_class($this);
51 '#maxlength' => self::EMAIL_MAX_LENGTH,
52 '#autocomplete_route_name' => FALSE,
54 [$class, 'processAutocomplete'],
55 [$class, 'processAjaxForm'],
56 [$class, 'processPattern'],
58 '#element_validate' => [
59 [$class, 'validateEmail'],
62 [$class, 'preRenderEmail'],
64 '#theme' => 'input__email',
65 '#theme_wrappers' => ['form_element'],
70 * Form element validation handler for #type 'email'.
72 * Note that #maxlength and #required is validated by _form_validate() already.
74 public static function validateEmail(&$element, FormStateInterface $form_state, &$complete_form) {
75 $value = trim($element['#value']);
76 $form_state->setValueForElement($element, $value);
78 if ($value !== '' && !\Drupal::service('email.validator')->isValid($value)) {
79 $form_state->setError($element, t('The email address %mail is not valid.', ['%mail' => $value]));
84 * Prepares a #type 'email' render element for input.html.twig.
86 * @param array $element
87 * An associative array containing the properties of the element.
88 * Properties used: #title, #value, #description, #size, #maxlength,
89 * #placeholder, #required, #attributes.
92 * The $element with prepared variables ready for input.html.twig.
94 public static function preRenderEmail($element) {
95 $element['#attributes']['type'] = 'email';
96 Element::setAttributes($element, ['id', 'name', 'value', 'size', 'maxlength', 'placeholder']);
97 static::setAttributes($element, ['form-email']);