A clean customer list in Magento starts with proper email validation. This guide walks through five implementation methods using working code snippets. You will see the drawbacks of traditional approaches and learn how Abstract API overcomes them for more reliable verification.
How to Implement Email Validation in Magento
Here are several methods to implement email validation in Magento. Each approach uses built-in framework features to check email addresses at different stages of the customer journey.
Native Front-End Rule: validate-email
The JavaScript library for Magento’s UI components and forms includes a rule called validate-email. When you attach this rule, it stops the form submission if an address fails the platform's regular expression check.
The framework's validation rules list explicitly contains validate-email. You can add the rule directly to a template or through UI component XML. The code below shows both implementations.
<!-- Example (phtml or .html template) -->
<input type="text"
name="email"
class="required-entry validate-email" />
<!-- Example (UI component xml) -->
<field name="email" sortOrder="10">
<settings>
<validation>
<rule name="required-entry" xsi:type="boolean">true</rule>
<rule name="validate-email" xsi:type="boolean">true</rule>
</validation>
</settings>
</field>
Core Server-Side Validator: Magento\Framework\Validator\EmailAddress
Any service layer call that accepts user input can use the framework’s email validator. This class is a thin wrapper around Laminas\Validator\EmailAddress, which Magento has used since version 2.4.6.
The code instantiates or injects the validator and then calls the isValid method. If the email is not valid, the code throws an InputException. Some developers prefer a Laminas static helper for zero allocations.
use Magento\Framework\Validator\EmailAddress;
public function execute(string $email): void
{
$validator = new EmailAddress();
if (!$validator->isValid($email)) {
throw new \Magento\Framework\Exception\InputException(
__('Email address is invalid')
);
}
}
Repository Plugin or Observer Gate
Because users can bypass client-side checks, many development teams choose to intercept the persistence layer. This provides a server-side gate to catch invalid data before it saves to the database.
You can create a beforeSave plugin for the CustomerRepositoryInterface or an observer on the customer_save_before event. The plugin runs inside the service contract, so it catches REST, GraphQL, and UI flows with one implementation.
The code gets the customer's email and uses the Laminas StaticValidator to execute the check. If the validation fails, it throws an InputException to prevent the save operation.
public function beforeSave(
\Magento\Customer\Api\CustomerRepositoryInterface $subject,
\Magento\Customer\Api\Data\CustomerInterface $customer,
$passwordHash = null
) {
$email = $customer->getEmail();
if (!\Laminas\Validator\StaticValidator::execute($email, 'EmailAddress')) {
throw new \Magento\Framework\Exception\InputException(__('Bad e-mail'));
}
return [$customer, $passwordHash];
}
Challenges of Magento Email Validation
Magento's built-in validation tools present several operational hurdles. These native methods often create inconsistencies and require ongoing maintenance to function correctly for modern email address formats.
- Client-side
validate-email
and server-side validators use different regex patterns. This drift means an address may pass in the browser but fail on the server, which creates an inconsistent user experience. - The default regex in core validators fails to recognize modern formats like international domains or plus-tagged addresses. Developers must override both JavaScript and PHP rules to accept these valid emails, which adds maintenance.
- Platform updates introduce risk. A past core update shipped with stricter validation that incorrectly flagged valid customer accounts as duplicates. This change broke the registration process for many stores until a fix was released.
- Third-party extensions often inject their own rules into the
validate-email
mixin. These custom patterns can conflict with each other or with core rules, which leads to unpredictable validation behavior across the storefront.
Validate Emails with Abstract API
Ensure your messages reach the inbox. Implement accurate email validation to protect your sender score.
Get started for free
How Abstract API Handles Email Validation in Magento
Abstract API addresses the core weaknesses of traditional validation methods. It provides a server-side checkpoint that moves far beyond the simple regex filters native to the platform.
- It runs DNS, SMTP, and provider-type checks in real time to confirm an email's legitimacy.
- The system scores each address for quality and returns an auto-correct suggestion when it detects a likely typo.
- It determines if a mailbox is deliverable, disposable, or a catch-all address, and also checks for dead MX records.
- The fast, stateless REST call eliminates bounce-induced penalties and fraud without a negative impact on the user experience during checkout or registration.
How to Add Abstract API to Your Dev Environment
Once you understand Abstract’s capabilities, you add its email validation API to your project with ease.
- Create an account on Abstract API and copy your Email Validation API key.
- From the Magento root directory, run the composer command to require the PHP email validation library.
- Store the key in your env.php file or under Stores → Configuration → Advanced → Developer.
- Create a custom module, then register an observer for customer_save_before or checkout_submit_before.
- Inside the observer, configure the API with your key and then call the verify method with the user's email.
- Use the response data to reject, correct, or flag the email and log the quality score for analytics.
composer require abstractapi/php-email-validation
Sample Email Validation Implementation with Abstract API
The following code shows a practical implementation within a Magento observer. It retrieves the customer's email during a save event. Then, it configures the API with the stored key and sends the email for verification.
If the API response shows the email is not deliverable or comes from a disposable provider, the code throws an exception. This action stops the process and prompts the user for a valid address.
$email = $observer->getEvent()->getCustomer()->getEmail();
\Abstractapi\EmailValidation\AbstractEmailValidation::configure(
$this->scopeConfig->getValue('dev/abstract/api_key')
);
$info = \Abstractapi\EmailValidation\AbstractEmailValidation::verify($email);
if ($info->deliverability !== 'DELIVERABLE' || $info->is_disposable_email->value) {
throw new \Magento\Framework\Exception\LocalizedException(
__('Please enter a valid email address.')
);
}
The API returns a detailed JSON object. Here is a sample response:
{
"email":"johnsmith@gmail.com",
"deliverability":"DELIVERABLE",
"quality_score":0.9,
"is_valid_format":{"value":true,"text":"TRUE"},
"is_free_email":{"value":true,"text":"TRUE"},
"is_disposable_email":{"value":false,"text":"FALSE"},
"is_mx_found":{"value":true,"text":"TRUE"},
"is_smtp_valid":{"value":true,"text":"TRUE"}
}
The deliverability field gives the main verdict, while quality_score expresses confidence. The boolean fields clarify the result with details on syntax, domain type, MX records, and the SMTP handshake. You can map these fields to hard rejections or soft warnings to maintain list hygiene without the block of real customers.
Final Thoughts
Traditional validation only confirms an email's format. It fails to detect undeliverable, disposable, or fraudulent addresses, which harms your sender reputation. Abstract API solves this with real-time checks that confirm an address is legitimate and safe to accept.
To reliably validate user emails, create an account on Abstract API and get your free API key.
Validate Emails with Abstract API
Protect your sender reputation and improve deliverability by validating every email address you collect.
Get started for free