Extending AEV
The advanced_email_validation.validator service validates an email address against the site's configured rules. Use it when you need to validate an address in your own code, or its included Event to react to and override the module's decisions.
Validating an address
Call validateEmail(). It returns an EmailValidationResult carrying the outcome and the message to show:
/** @var \Drupal\advanced_email_validation\AdvancedEmailValidatorInterface $validator */
$validator = \Drupal::service('advanced_email_validation.validator');
$result = $validator->validateEmail('person@example.com');
if (!$result->isValid()) {
// $result->errorCode is the failure code.
// $result->message is the configured, translatable message for it.
\Drupal::messenger()->addError($result->message);
}The result exposes:
isValid()- whether the address passed.errorCode- the failure code (0 when valid). The codes are the constants on\EmailValidator\EmailValidator(FAIL_BASIC,FAIL_MX_RECORD,FAIL_DISPOSABLE_DOMAIN,FAIL_FREE_PROVIDER,FAIL_BANNED_DOMAIN,FAIL_RFC5322, andFAIL_CUSTOMwhen a subscriber rejected the address).message- the message to show when invalid, or an empty string when valid.
Overriding the rules for a single call
validateEmail() takes optional configuration and message overrides, so one call can use rules other than the site defaults:
$result = $validator->validateEmail('person@example.com', [
'checkMxRecords' => TRUE,
'checkFreeEmail' => TRUE,
'freeList' => ['example.com'],
]);The full signature is validateEmail(string $email, array $configOverrides = [], array $errorMessages = []). The override keys (checkMxRecords, checkBannedListedEmail, checkDisposableEmail, checkFreeEmail, bannedList, disposableList, freeList) match the library's policy; $errorMessages is keyed by rule.
Reacting to or changing the result with an event
Every validateEmail() call dispatches an EmailValidationEvent, whether the address passed or failed. Subscribe to it to log validations, or to override the module's decision. A subscriber can:
accept()- treat the address as valid even though the rules rejected it (an allowlist).reject($message)- treat the address as invalid even though the rules passed it (a custom rule). This is reported asFAIL_CUSTOM.setMessage($message)- change the message shown to the user without changing the outcome.
It also exposes getEmail(), getErrorCode(), isValid(), and getMessage() for inspecting the current state.
An override flows back through the returned EmailValidationResult, and through the user-account validation and the Webform handler too, since they both use this service.
Example: allow your own domain, require corporate addresses
namespace Drupal\my_module\EventSubscriber;
use Drupal\advanced_email_validation\Event\EmailValidationEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class EmailPolicySubscriber implements EventSubscriberInterface {
public static function getSubscribedEvents(): array {
return [EmailValidationEvent::class => 'onValidate'];
}
public function onValidate(EmailValidationEvent $event): void {
// Always allow our own domain, whatever the rules decided.
if (str_ends_with($event->getEmail(), '@example.com')) {
$event->accept();
return;
}
// Reject anything that is not a corporate address.
if (!str_ends_with($event->getEmail(), '@corp.example')) {
$event->reject('Please use your corporate email address.');
}
}
}Register the subscriber as a service in your module's *.services.yml:
services:
my_module.email_policy_subscriber:
class: Drupal\my_module\EventSubscriber\EmailPolicySubscriber
tags:
- { name: event_subscriber }Upgrading from 1.x or 2.x
Earlier versions exposed two methods, validate() (returning an error code) and errorMessageFromCode() (returning the message). They were deprecated in 1.3.0 and 2.1.0 and are removed in 3.0. Replace them with a single validateEmail() call, which returns both the code and the message in one EmailValidationResult.
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion