Introduction
In the ever-evolving landscape of web development, the integrity of user-provided data stands as a pivotal concern. The prevalence of fake email, individuals attempting to register or submit information using invalid or non-existent email addresses has become a common challenge for developer. These deceptive practices not only undermine the accuracy of user databases but also pose potential threats to the functionality and security of web applications.
In this post, we embark on a journey to address this challenge by exploring the creation of a custom email validation rule in Laravel. This rule aims not just to check for syntactical correctness but to actively verify the existence and validity of email addresses in real-time. By understanding the motivations behind fake emails and crafting a solution that goes beyond conventional validation, we empower developers to fortify their applications against deceptive practices and elevate the reliability of user data.
Why the Battle Against Fake Emails Matters and the Limitations of Default Validation Rules
Fake emails are not merely a nuisance; they pose significant challenges to web applications. Malicious actors often exploit contact forms or registration processes with fabricated email addresses, leading to inaccurate user data. This not only skews analytics but can also be used for malicious activities, such as spam or fraudulent registrations. To ensure the accuracy of user databases and maintain the integrity of web applications, a robust email validation mechanism is imperative.
Laravel provides out-of-the-box email validation rules like email
and email:rfc
which excel at ensuring basic syntactical correctness. However, these rules fall short when it comes to verifying the actual existence and validity of an email address, hence the need for a custom solution becomes apparent.
Crafting a Custom Rule for Real-Time Email Verification
To address the shortcomings of default rules, we introduce a custom email validation rule. This rule leverages real-time verification, actively checking whether an email address exists. By tapping into external services, developers can go beyond the surface-level syntax and ensure that the provided email addresses are genuine and deliverable.
Register an account on ZeroBounce and get an API KEY
There are a handle full of email validation service that can be choosing from, but we are using ZeroBounce in the post for its easy of use. A free account gives you 100 free credits every month which are used to validate email addresses.
- Sign up for ZeroBounce account.
- Obtain your API key from the ZeroBounce dashboard.
Create a custom Validation Rule
Create a new rule in Laravel with the command
php artisan make:rule ValidEmailRule
// app/Rules/ValidEmailRule.php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Http;
class ValidEmailRule implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$apiKey = "YOU_API_KEY_FROM_ZEROBOUNCE";
$apiUrl = "https://api.zerobounce.net/v2/validate?email={$value}&api_key={$apiKey}";
try {
$response = Http::get($apiUrl);
$data = $response->json();
$allowedStatuses = ['valid', 'catch-all'];
if (!in_array($data['status'], $allowedStatuses)) {
$fail("The {$attribute} is not a valid email address.");
}
} catch (\Exception $e) {
$fail("Error validating the provided {$attribute}. Please confirm and provide a valid {$attribute}");
}
}
}
Using the Custom Laravel Validation
Seamlessly integrate the custom email validation rule into Laravel's validation process. We provide a hands-on example of using the custom rule in a controller or request.
// app/Http/Controllers/YourController.php
use App\Rules\ValidEmailRule;
use Illuminate\Support\Facades\Validator;
// ...
public function yourMethod(Request $request)
{
$request->validate([
'email' => ['required', 'email', new ValidEmailRule],
]);
// Validation passed
// Rest of your method
}
We still use the default email
validation to check syntactical correctness and only call the custom validation only when that default validation is passed.
Conclusion
With the understanding of the limitations of default validation rules, crafting a custom rule, and seamlessly integrating it into Laravel's validation process, developers can ensure their applications validate emails effectively.
Elevate your Laravel applications by going beyond the basics of email validation, providing users with a seamless experience and maintaining data integrity. Strengthen your development toolkit with custom validation rules that make a difference.