0

How can I setup custom required field validation message for a text field in my custom form. I tried below code. But it is not working. It always showing 'Please fill out this field'.

$form['first_name'] = [
  '#type' => 'textfield',
  '#title' => $this->t('First Name'),
  '#default_value' => $this->store->get('first_name') ? $this->store->get('first_name') : '',
  '#required_but_empty' => $this->t('Please enter First Name'),
  '#required' => TRUE,
];
  • How we will manage clientside validation in drupal 8 form? By using custom jQuery or Drupal 8 has its own way? – ARUN Jun 6 '17 at 10:37
0

How do I add a custom validation to an existing form/field?

If you want to add your custom validator in addition to the default, you will have to add something like this in hook_form_FORM_ID_alter (or similar):

$form['#validate'][] = 'my_test_validate';

  • In Drupal 8 client side validation coming by default for form fields.. How can I add additional client side validation to custom form fields? – ARUN Jun 6 '17 at 10:16
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';

The property #required_but_empty is set automatically during validation when the required field is empty. This is an internal property and is not set manually. It allows #element_validate handlers to set a custom required error message, but without having to re-implement the complex logic to figure out whether the field value is empty.

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.