In a modal form, i've got e email field that is required.

  • when the field is wrong, a error message is well displayed
  • when the field is empty, $form_state->hasAnyErrors() is true but there is no error message
  • when i whant to set the error message in the form validation function, it's stay empty !

in BuildForm :

  $form['email'] = array(
            '#type' => 'email',
            '#required' => true,
            '#attributes' => [
                'placeholder' => t('Your email'),
                "data-nluid" => $nluid
$form['actions']['submit'] = [
                '#type' => 'submit',
                '#value' => t('Suscribe'),
                '#ajax' => [
                    'callback' => '::submitModalFormAjax',
                    'wrapper' => 'newsletter_add_modal', 
                    'event' => 'click'

in validateForm

 public function validateForm(array &$form, FormStateInterface $form_state) {
        $emailValue = $form_state->getValue("email");
        if (!\Drupal::service('email.validator')->isValid($emailValue) || trim($emailValue) == "") {

         $form_state->setErrorByName('email', "Email is required and must be valid");    
         //binding form_state->getError($form['email']) show empty string

in submitModalFormAjax

 // If there are any form errors, re-display the form.
        if ($form_state->hasAnyErrors()) { 
            $response->addCommand(new ReplaceCommand('#newsletter_add_modal', $form));
        } else {
 // else, exec success behavior

What am I doing wrong?

1 Answer 1


I know i'm a bit late but the problem is that the email field is required. Required fields may not be empty, otherwise it will throw an error.

If you wish to show an error message you need a form element to catch these messages.

 $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.