Ensuring email addresses are valid is a key part of maintaining data integrity in any Laravel application. We will walk through four native validation techniques, complete with code snippets, before highlighting their shortcomings and demonstrating how Abstract API provides a more robust solution.
How to Implement Email Validation in Laravel
Laravel offers several built-in methods to confirm email address validity. Here are four common approaches, from basic syntax checks to more advanced, custom rule creation for your application.
The Baseline Rule
Laravel includes a default "email" validation rule. This rule uses the `Egulias\EmailValidator` library to perform its checks. By default, it validates the email's syntax against the RFC 5322 standard. This process confirms the format is correct but does not check for deliverability.
$request->validate([
'email' => ['required', 'string', 'email'],
]);
The Parameterized Rule
You can enhance the basic "email" rule with specific parameters. These parameters are added as a colon-separated string. They allow for more rigorous checks beyond simple syntax validation.
Egulias runs these checks sequentially. The available flags include:
- "rfc" or "strict": These flags switch between different levels of RFC compliance validation.
- "dns": This check looks for a domain's MX record. It requires the PHP "intl" extension to function.
- "spoof": This detects potential Unicode homograph attacks and also depends on the "intl" extension.
- "filter" or "filter_unicode": These options use PHP’s native "filter_var()" function as a fallback.
$request->validate([
'email' => 'required|email:strict,dns,spoof',
]);
The Fluent Builder
Starting with Laravel 11.38, a fluent interface for the email rule is available. This approach uses the "Rule::email()" method to construct a typed validation object. It improves code readability and makes the developer's intent explicit.
This method also helps prevent common errors from string parsing. The fluent methods correspond directly to the parameterized flags, as noted in a Laravel News update. For example, "validateMxRecord()" is the same as the "dns" flag.
use Illuminate\Validation\Rule;
$request->validate([
'email' => [
'required',
Rule::email()
->rfcCompliant(strict: true)
->validateMxRecord()
->preventSpoofing(),
],
]);
A Custom Rule
For more control, you can create a custom validation rule. This involves a new class that implements Laravel's "Rule" contract. This gives you the flexibility to define your own validation logic.
The "passes" method contains the core logic. It first uses `Egulias\EmailValidator` for a syntax check. If that passes, it checks for the domain's MX record. The "message" method defines the error text. You then use the rule by instantiating it in your validation array.
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
class DeliverableEmail implements \Illuminate\Contracts\Validation\Rule {
public function passes($attr, $value) {
$v = new EmailValidator;
if (! $v->isValid($value, new RFCValidation)) {
return false;
}
[,$domain] = explode('@', $value, 2);
return checkdnsrr($domain, 'MX');
}
public function message() {
return 'Address is not deliverable.';
}
}
The Challenges of Native Laravel Email Validation
Laravel's built-in validation methods, while convenient, introduce significant drawbacks. These issues can compromise data quality, application performance, and the overall reliability of your email verification process.
- The baseline email:rfc rule accepts syntactically valid but undeliverable addresses. This includes emails with spaces or comments, which most mail providers reject, so you collect useless data.
- The email:dns flag adds latency with a blocking DNS lookup on every request. A known bug also accepts any A record, which creates false positives for domains without MX records.
- Native methods lack full Unicode support. Both filter_var and the default validator fail to parse valid international addresses with non-ASCII characters unless you implement custom punycode logic yourself.
- Validation behavior often differs between local and production environments. Discrepancies in database collation, PHP versions, or DNS resolvers can cause authentication failures and bugs that are difficult to reproduce.
Validate Emails with Abstract API
Implement email validation in your Laravel application to improve data integrity and user experience.
Get started for free
How Abstract API Handles Email Validation in Laravel
Abstract API addresses the core weaknesses of traditional methods through real-time SMTP handshakes, identification of low-quality addresses, and a detailed quality score.
- It runs MX and real-time SMTP handshakes without open socket or grey-listing delays inside your PHP worker.
- It flags free, disposable, role, and catch-all domains and proposes autocorrects for common typos.
- It returns a numeric quality score and categorical deliverability, which lets you apply business-specific thresholds.
- It uses a constantly trained machine learning model backed by billions of validations for low-latency results.
How to Add Abstract API to Your Dev Environment
Once you understand Abstract’s capabilities, you can add its email validation API to your project with ease.
- Create an Abstract account, enable “Email Verification & Validation,” and copy the key.
- Add ABSTRACT_EMAIL_KEY=your_key to your .env file and run php artisan config:cache.
- Ensure you have an HTTP client. Use composer require guzzlehttp/guzzle for Laravel versions before 7. Otherwise, the built-in Illuminate\Support\Facades\Http works.
- Add 'abstract' => ['key' => env('ABSTRACT_EMAIL_KEY')] to your config/services.php file.
- Create a rule that calls the API endpoint with your api_key and email parameters. This rule should interpret the deliverability and quality_score fields.
- Reference that rule in a FormRequest or validator, for example: 'email' => ['required', new \App\Rules\AbstractEmail].
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Http;
class AbstractEmail implements Rule
{
public function passes($attribute, $value)
{
$r = Http::timeout(3)->get(
'https://emailvalidation.abstractapi.com/v1/',
['api_key' => config('services.abstract.key'), 'email' => $value]
)->throw()->json();
return $r['deliverability'] === 'DELIVERABLE'
&& !$r['is_disposable_email']['value']
&& $r['quality_score'] >= 0.8;
}
public function message() { return 'Unable to verify this email address.'; }
}
Sample Email Validation Implementation with Abstract API
The custom rule above sends the user-provided email to Abstract API. It then checks the response to confirm the address is deliverable, is not a disposable domain, and meets a quality score of at least 0.8. If these conditions pass, the validation succeeds. Below is a sample JSON response from the API for a valid email.
{
"email": "johnsmith@gmail.com",
"autocorrect": "",
"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_role_email": { "value": false, "text": "FALSE" },
"is_catchall_email": { "value": false, "text": "FALSE" },
"is_mx_found": { "value": true, "text": "TRUE" },
"is_smtp_valid": { "value": true, "text": "TRUE" }
}
The response contains several key fields. The "deliverability" field combines all checks into a simple status like "DELIVERABLE". The "quality_score" allows you to tune acceptance thresholds. Granular "is_*" fields provide context on whether an email is disposable or from a free provider, which lets your policies differ for various domains.
Final Thoughts
Traditional validation stops at syntax and DNS checks, so it misses disposable addresses and offers no real deliverability score. Abstract API moves beyond these limits with real-time SMTP handshakes and a numeric quality score.
To reliably validate user emails, create an account on Abstract API and get your free API key.
Validate Emails with Abstract API
Stop fake sign-ups and improve data quality in your Laravel app with proper email validation.
Get started for free