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'));
}
}
}