4

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

3

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.

13

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);
}
  • 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 '18 at 1:01

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.