0

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

Try this, it might work.

$name = $form_state->getValue('name');
if (empty($name)) {
   $form_state->setErrorByName('name', $this->t('Email is required.'));
}
  • I commented required true then already apply ur way. Then it works fine. Can we do it like require = true & alter message? – Ankit Shah Sep 27 '17 at 5:31
  • 2
    @AnkitShah, the required message is not from Drupal, it's the browser based html5 validation. See stackoverflow.com/questions/5272433/… – 4k4 Sep 27 '17 at 6:36
  • Talking about '#required' => TRUE,. Drupal server side error message not JS – Ankit Shah Sep 27 '17 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. – 4k4 Sep 27 '17 at 7:24
0

Set the property "required_error" to form element. This is available in Drupal 8.6. For ex-

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

To make this work, firstly you will have to disable HTML 5 validation on the form.

$form['#attributes']['novalidate'] = 'novalidate';
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, privacy policy and cookie policy

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