Laravel 5.6内置邮箱验证器误判合法长前缀邮箱地址
Hey there, let's break down why your long email address is failing validation and how to fix it.
The Root Cause
Laravel 5.6 relies on the egulias/email-validator package for its default email validation rule. This package strictly follows RFC 5321, which states the local part of an email (everything before the @) can be at most 64 octets (bytes). Your email's local part—all those 1s plus thebestemail—far exceeds this 64-character limit, which is why the validation throws an error.
While you might consider the email "theoretically valid," most mainstream email providers enforce the 64-character limit for the local part anyway. But if your use case specifically requires supporting longer local parts, here are two practical solutions:
Solution 1: Create a Custom Validation Rule
Build a custom rule that relaxes the local part length restriction.
Generate the custom rule file via Artisan:
php artisan make:rule ValidEmailOpen the generated
app/Rules/ValidEmail.phpfile and update thepasses()method with your preferred validation logic. For example, to allow up to 254 characters in the local part (a common maximum for systems that don't strictly adhere to RFC 5321):<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class ValidEmail implements Rule { public function passes($attribute, $value) { // Custom regex allowing longer local part $pattern = '/^[a-zA-Z0-9._%+-]{1,254}@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/'; return preg_match($pattern, $value) === 1; } public function message() { return 'The :attribute must be a valid email address.'; } }Use your custom rule in validation (in a controller or form request class):
use App\Rules\ValidEmail; $request->validate([ 'email' => ['required', new ValidEmail], ]);
Solution 2: Override the Default Email Validation Rule Globally
If you want to replace Laravel's default email rule across your entire application, update your AppServiceProvider:
- Open
app/Providers/AppServiceProvider.phpand modify theboot()method:<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Validation\Validator; class AppServiceProvider extends ServiceProvider { public function boot() { Validator::extend('email', function ($attribute, $value, $parameters, $validator) { // Use PHP's filter_var (more lenient than Laravel's default rule) return filter_var($value, FILTER_VALIDATE_EMAIL) !== false; // OR use the same custom regex from Solution 1 // $pattern = '/^[a-zA-Z0-9._%+-]{1,254}@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/'; // return preg_match($pattern, $value) === 1; }); } }
A Quick Heads-Up
Even if you relax the validation, many email services will still reject messages sent to addresses with local parts longer than 64 characters. Only adjust this rule if you're certain your target audience uses systems that support longer local parts.
内容的提问来源于stack exchange,提问作者David Simon

