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.
17 * $form['email'] = array(
19 * '#title' => $this->t('Email'),
23 * @see \Drupal\Core\Render\Element\Render\Textfield
25 * @FormElement("email")
27 class Email extends FormElement {
30 * Defines the max length for an email address
32 * The maximum length of an email address is 254 characters. RFC 3696
33 * specifies a total length of 320 characters, but mentions that
34 * addresses longer than 256 characters are not normally useful. Erratum
35 * 1690 was then released which corrected this value to 254 characters.
36 * @see http://tools.ietf.org/html/rfc3696#section-3
37 * @see http://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690
39 const EMAIL_MAX_LENGTH = 254;
44 public function getInfo() {
45 $class = get_class($this);
49 '#maxlength' => self::EMAIL_MAX_LENGTH,
50 '#autocomplete_route_name' => FALSE,
52 [$class, 'processAutocomplete'],
53 [$class, 'processAjaxForm'],
54 [$class, 'processPattern'],
56 '#element_validate' => [
57 [$class, 'validateEmail'],
60 [$class, 'preRenderEmail'],
62 '#theme' => 'input__email',
63 '#theme_wrappers' => ['form_element'],
68 * Form element validation handler for #type 'email'.
70 * Note that #maxlength and #required is validated by _form_validate() already.
72 public static function validateEmail(&$element, FormStateInterface $form_state, &$complete_form) {
73 $value = trim($element['#value']);
74 $form_state->setValueForElement($element, $value);
76 if ($value !== '' && !\Drupal::service('email.validator')->isValid($value)) {
77 $form_state->setError($element, t('The email address %mail is not valid.', ['%mail' => $value]));
82 * Prepares a #type 'email' render element for input.html.twig.
84 * @param array $element
85 * An associative array containing the properties of the element.
86 * Properties used: #title, #value, #description, #size, #maxlength,
87 * #placeholder, #required, #attributes.
90 * The $element with prepared variables ready for input.html.twig.
92 public static function preRenderEmail($element) {
93 $element['#attributes']['type'] = 'email';
94 Element::setAttributes($element, ['id', 'name', 'value', 'size', 'maxlength', 'placeholder']);
95 static::setAttributes($element, ['form-email']);