8

I have a a kind of conditional field for a sign up form where the user can optionally sign up with a mobile number or an email address.

I'm trying out a custom form validate eg.

  function signup_validate($form, FormStateInterface $form_state) {
    $mobile = $form_state->getValue('field_mobile');
    $email = $form_state->getValue('field_email_address');

    if ($email[0]['value'] != '' || $mobile[0]['value'] != '') {
      $form_state->clearErrors();
    }
  }

Now clearErrors(); obviously clears all errors for the form even if other fields are invalid, I want to know how to clear the error only for field_mobile or field_email_address

2 Answers 2

2

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.

1
  • States affect only client side validation, not server side. "Since states are driven by JavaScript only, it is important to understand that all states are applied on presentation only" > drupal.org/docs/drupal-apis/form-api/…
    – Christian
    Jul 27, 2022 at 8:22
27

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);
}
4
  • For me this requirement it's needed on credit card fields required with no name attribute and for security reasons not received on my server, only a token from my payment provider.
    – ropic
    Oct 27, 2018 at 1:01
  • Ended up needing to use for a plugin configuration form in validateConfigurationForm() as I couldn't get #states to function as expected.
    – Mrweiner
    Apr 23, 2020 at 0:13
  • It's working for me May 12, 2022 at 12:24
  • Good answer. Should be the accepted answer.
    – Christian
    Jul 27, 2022 at 8:23

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.