Reputation: 19
Currently I am using a renderable array to generate a form which has a HTML 5 email field on it.
Originally the form accepted a single email address. It needs to be modified to accept a separated list of email addresses AND pass Drupals email field validation.
The current code is
$form['an_email_field'] = [
'#type' => 'email',
'#title' => $this->t('enter an email'),
'#default_value' => '[email protected]',
'#attributes' =>['multiple']
]
The '#attributes' => ['multiple']
property adds multiple
to the generated HTML fields attribute list which means HTML 5 will accept the input if multiple email addresses are provided.
But if multiple email addresses are provided Drupal's email validation fails.
Is it possible to make Drupal 8 accept multiple comma separated email addresses when '#type' => 'email'
is used?
Can this be done without creating a custom validator?
Notes
'#type' => 'email'
to '#type' => 'textfield'
is not desired unless there is some way to still set the fields type (according the HTML) to email.Upvotes: 2
Views: 1511
Reputation: 5374
With the Webform module installed you could simply use the webform_email_multiple
element.
$form['an_email_field'] = [
'#type' => 'webform_email_multiple',
'#title' => $this->t('enter an email'),
'#default_value' => '[email protected]',
];
Otherwise you may want to use a textfield
or textarea
element instead and then do the element or form validation on your own using the email.validator
service after you exploded the comma-separated string. Here's how the validateEmail
function does it on email
elements:
$value = trim($element['#value']);
$form_state
->setValueForElement($element, $value);
if ($value !== '' && !\Drupal::service('email.validator')
->isValid($value)) {
$form_state
->setError($element, t('The email address %mail is not valid.', [
'%mail' => $value,
]));
}
Upvotes: 1