1

I have below code

$form['name'] = [
      '#type' => 'textfield',
      //'#title' => $this->t('Email'),
      '#size' => 60,
      '#maxlength' => USERNAME_MAX_LENGTH,
      '#default_value' => $form_state->getValue('name', ''),
      '#required' => TRUE,
      '#attributes' => [
        'placeholder' => $this->t('Email'),
        'autocorrect' => 'none',
        'autocapitalize' => 'none',
        'spellcheck' => 'false',
        'autofocus' => 'autofocus',
      ],
    ];

When I comment title it shows blank. I would like to change error message of the required field.

In the validation handler, I tried with this code.

if ($form_state->isValueEmpty('name')) {
  $form_state->setErrorByName('name', $this->t('Email is required.')); 
}

It's not showing the error message.

I would like to keep the form element required and alter the error message.

1

3 Answers 3

2

Set the required_error property as in the following code. This is available in Drupal 8.6.

$form['name'] = [
  '#type' => 'textfield',
  '#size' => 60,
  '#default_value' => $form_state->getValue('name', ''),
  '#required' => TRUE,
  '#required_error' => t('Please select something.'),
];

To make this work, you will have to disable HTML5 validation on the form.

$form['#attributes']['novalidate'] = 'novalidate';
1
  • Worked for me without this: $form['#attributes']['novalidate'] = 'novalidate'; Commented Jun 18, 2020 at 14:48
1

Try this, it might work.

$name = $form_state->getValue('name');
if (empty($name)) {
   $form_state->setErrorByName('name', $this->t('Email is required.'));
}
4
  • I commented required true then already apply ur way. Then it works fine. Can we do it like require = true & alter message?
    – user9589
    Commented Sep 27, 2017 at 5:31
  • 2
    @AnkitShah, the required message is not from Drupal, it's the browser based html5 validation. See stackoverflow.com/questions/5272433/…
    – 4uk4
    Commented Sep 27, 2017 at 6:36
  • Talking about '#required' => TRUE,. Drupal server side error message not JS
    – user9589
    Commented Sep 27, 2017 at 6:50
  • 1
    @AnkitShah, but #required sets a required attribute on the input element and then the browser based html5 (not JS) validation prevents the server side validation message.
    – 4uk4
    Commented Sep 27, 2017 at 7:24
0

For drupal 8 working for me, Remove '#required' => TRUE,

In Form validation you can write your message what you want.

public function validateForm(array &$form, FormStateInterface $form_state) {

$name = $form_state->getValue(['name']);

if(!$name) {
    $form_state->setErrorByName('name', $this->t('Enter valid name.'));
}
}

Your Answer

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