0

I am trying to implement a custom validation for webform. I need to validate if user entered email is valid or not. For that I have altered the webform using event subscriber and assigned a validation handler. But validation handler is not getting called. The configured webform is ajax enabled. Below is my code.


namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\hook_event_dispatcher\HookEventDispatcherInterface;

/**
 * Altering drupal forms with hook_event_dispatcher.
 */
class ContactWebFormFormAlterEventSubScriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      HookEventDispatcherInterface::FORM_ALTER => 'hookFormAlter',
    ];
  }

  /**
   * Altering form array from here.
   */
  public function hookFormAlter($event) {
    if ( strpos( $event->getFormId(), 'webform_submission_contact_us' ) !== false ) {
      $form = $event->getForm();
      $form['#validate'][] = '::mymodule_webform_submission_contact_us_validate';
      $event->setForm($form);
    }
  }

  /**
   * Altering form array from here.
   */
  public function mymodule_webform_submission_contact_us_validate(array &$form, FormStateInterface $form_state) {
    $email = $form_state->getValue('email');
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $form_state->setErrorByName('email', $this->t('Email address is invalid'));
    }
  }
}

2
  • You are not subscribing to a real Drupal event, the module you use dispatches an event from a form alter hook and it is the same as if you would use a form alter hook directly. So you can look for similar posts concerning form alter hooks and my guess would be you need to add the validate callback to the form element and not to the top level of $form.
    – 4uk4
    Commented Mar 11, 2020 at 14:12
  • On a side note, webform supports plugins to add a validate handler (if you want to use OOP code).
    – 4uk4
    Commented Mar 11, 2020 at 14:31

1 Answer 1

0

You should use a custom webform plugin handler for that.

More information here: https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-add-custom-validation-to-a-webform-element

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.