Drupal - unset form error for specific field

While I agree with the accepted answer, one way to accomplish your goal is to:

  1. Assign the form errors to a variable, such as $form_errors
  2. Clear all form errors from $form_state
  3. Remove the particular form error from $form_errors
  4. Loop through the remaining $form_errors, re-setting them to $form_state.

So to clear the field_mobile error you would use the following code:

// Temporarily store all form errors.
$form_errors = $form_state->getErrors();

// Clear the form errors.
$form_state->clearErrors();

// Remove the field_mobile form error.
unset($form_errors['field_mobile']);

// Now loop through and re-apply the remaining form error messages.
foreach ($form_errors as $name => $error_message) {
  $form_state->setErrorByName($name, $error_message);
}

Instead of removing the error, you should make sure that only the needed validation errors are set in the first place.

For example, you could use '#states' in your form elements to set 'required' depending on the user input of the other field.

Tags:

Forms

8