表单验证
这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。
验证
简介
Laravel 提供了多种不同的方式来验证应用程序接收到的数据。最常见的方式是使用所有传入 HTTP 请求都可以使用的 validate 方法。不过,我们也会讨论其他验证方式。
Laravel 包含了各种方便的验证规则,你可以将这些规则应用于数据,甚至可以验证某个值在指定数据库表中是否唯一。我们将详细介绍这些验证规则中的每一项,以便你熟悉 Laravel 的所有验证功能。
验证快速入门
为了了解 Laravel 强大的验证功能,让我们来看一个完整的示例,其中包括验证表单以及向用户显示错误消息。通过阅读这个高层次的概述,你将能够对如何使用 Laravel 验证传入的请求数据有一个良好的总体理解:
定义路由
首先,假设我们在 routes/web.php 文件中定义了以下路由:
use App\Http\Controllers\PostController;
Route::get('/post/create', [PostController::class, 'create']);
Route::post('/post', [PostController::class, 'store']);
GET 路由将显示一个供用户创建新博客文章的表单,而 POST 路由会将新的博客文章存储到数据库中。
创建控制器
接下来,让我们看一个用于处理这些路由传入请求的简单控制器。我们暂时将 store 方法留空:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class PostController extends Controller
{
/**
* 显示用于创建新博客文章的表单。
*/
public function create(): View
{
return view('post.create');
}
/**
* 存储新的博客文章。
*/
public function store(Request $request): RedirectResponse
{
// 验证并存储博客文章...
$post = /** ... */
return to_route('post.show', ['post' => $post->id]);
}
}
编写验证逻辑
现在,我们可以在 store 方法中填入用于验证新博客文章的逻辑。为此,我们将使用 Illuminate\Http\Request 对象提供的 validate 方法。如果验证规则通过,你的代码将继续正常执行;但是,如果验证失败,将抛出一个 Illuminate\Validation\ValidationException 异常,并且会自动向用户返回适当的错误响应。
如果在传统 HTTP 请求期间验证失败,将会生成一个重定向到上一个 URL 的响应。如果传入请求是 XHR 请求,则会返回一个包含验证错误消息的 JSON 响应。
为了更好地理解 validate 方法,让我们回到 store 方法:
/**
* 存储新的博客文章。
*/
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
// 博客文章有效...
return redirect('/posts');
}
如你所见,验证规则被传递给 validate 方法。不用担心——所有可用的验证规则都有文档说明。再次说明,如果验证失败,会自动生成适当的响应。如果验证通过,我们的控制器将继续正常执行。
此外,你还可以使用 validateWithBag 方法验证请求,并将所有错误消息存储在一个命名错误包中:
$validated = $request->validateWithBag('post', [
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
在第一次验证失败时停止
有时,你可能希望某个属性在第一次验证失败后就停止继续执行验证规则。为此,可以为该属性指定 bail 规则:
$request->validate([
'title' => ['bail', 'required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
在这个示例中,如果 title 属性上的 unique 规则验证失败,则不会再检查 max 规则。规则将按照它们被指定的顺序进行验证。
关于嵌套属性的说明
如果传入的 HTTP 请求包含“嵌套”字段数据,你可以在验证规则中使用“点”语法来指定这些字段:
$request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'author.name' => ['required'],
'author.description' => ['required'],
]);
另一方面,如果你的字段名称中包含一个字面意义上的句点,你可以通过使用反斜杠转义该句点,明确防止它被解释为“点”语法:
$request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'v1\.0' => ['required'],
]);
显示验证错误
那么,如果传入请求中的字段没有通过给定的验证规则会怎样?如前所述,Laravel 会自动将用户重定向回他们之前的位置。此外,所有验证错误和请求输入都会自动被闪存到 session 中。
Illuminate\View\Middleware\ShareErrorsFromSession 中间件会将一个 $errors 变量共享给应用程序的所有视图,该中间件由 web 中间件组提供。当应用了该中间件后,视图中将始终可以使用 $errors 变量,因此你可以方便地假定 $errors 变量始终已定义,并且可以安全使用。$errors 变量将是一个 Illuminate\Support\MessageBag 实例。有关如何使用此对象的更多信息,请查看其文档。
因此,在我们的示例中,当验证失败时,用户将被重定向到控制器的 create 方法,从而允许我们在视图中显示错误消息:
<!-- /resources/views/post/create.blade.php -->
<h1>创建文章</h1>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<!-- 创建文章表单 -->
自定义错误消息
Laravel 的每个内置验证规则都有一条错误消息,这些消息位于应用程序的 lang/en/validation.php 文件中。如果你的应用程序没有 lang 目录,可以使用 lang:publish Artisan 命令让 Laravel 创建它。
在 lang/en/validation.php 文件中,你会找到每条验证规则对应的翻译条目。你可以根据应用程序的需要自由更改或修改这些消息。
此外,你还可以将此文件复制到其他语言目录中,以便将这些消息翻译成应用程序所使用的语言。要了解更多关于 Laravel 本地化的信息,请查看完整的本地化文档。
[!警告]
默认情况下,Laravel 应用程序骨架不包含lang目录。如果你想自定义 Laravel 的语言文件,可以通过lang:publishArtisan 命令发布它们。
XHR 请求和验证
在这个示例中,我们使用传统表单向应用程序发送数据。然而,许多应用程序会从由 JavaScript 驱动的前端接收 XHR 请求。在 XHR 请求期间使用 validate 方法时,Laravel 不会生成重定向响应。相反,Laravel 会生成一个包含所有验证错误的 JSON 响应。这个 JSON 响应会以 422 HTTP 状态码发送。
@error 指令
你可以使用 @error Blade 指令快速判断某个给定属性是否存在验证错误消息。在 @error 指令中,你可以输出 $message 变量来显示错误消息:
<!-- /resources/views/post/create.blade.php -->
<label for="title">文章标题</label>
<input
id="title"
type="text"
name="title"
class="@error('title') is-invalid @enderror"
/>
@error('title')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
如果你正在使用命名错误包,可以将错误包的名称作为第二个参数传递给 @error 指令:
<input ... class="@error('title', 'post') is-invalid @enderror">
重新填充表单
当 Laravel 因验证错误生成重定向响应时,框架会自动将请求中的所有输入闪存到 session 中。这样做是为了让你能够在下一次请求期间方便地访问这些输入,并重新填充用户之前尝试提交的表单。
要获取上一次请求中闪存的输入,可以在 Illuminate\Http\Request 实例上调用 old 方法。old 方法会从 session 中取出之前闪存的输入数据:
$title = $request->old('title');
Laravel 还提供了一个全局的 old 辅助函数。如果你在 Blade 模板 中显示旧输入,使用 old 辅助函数来重新填充表单会更加方便。如果给定字段不存在旧输入,则会返回 null:
<input type="text" name="title" value="{{ old('title') }}">
关于可选字段的说明
默认情况下,Laravel 会在应用程序的全局中间件栈中包含 TrimStrings 和 ConvertEmptyStringsToNull 中间件。因此,如果你不希望验证器将 null 值视为无效,通常需要将“可选”请求字段标记为 nullable。例如:
$request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
'publish_at' => ['nullable', 'date'],
]);
在这个示例中,我们指定 publish_at 字段可以是 null,也可以是一个有效的日期表示。如果没有在规则定义中添加 nullable 修饰符,验证器会将 null 视为无效日期。
验证错误响应格式
当你的应用程序抛出 Illuminate\Validation\ValidationException 异常,并且传入的 HTTP 请求期望接收 JSON 响应时,Laravel 会自动为你格式化错误消息,并返回一个 422 Unprocessable Entity HTTP 响应。
下面,你可以查看一个验证错误的 JSON 响应格式示例。请注意,嵌套的错误键会被扁平化为“点”表示法格式:
{
"message": "The team name must be a string. (and 4 more errors)",
"errors": {
"team_name": [
"The team name must be a string.",
"The team name must be at least 1 characters."
],
"authorization.role": [
"The selected authorization.role is invalid."
],
"users.0.email": [
"The users.0.email field is required."
],
"users.2.email": [
"The users.2.email must be a valid email address."
]
}
}
表单请求验证
创建表单请求
对于更复杂的验证场景,你可能希望创建一个“表单请求”。表单请求是自定义的请求类,它们封装了自身的验证和授权逻辑。要创建一个表单请求类,你可以使用 make:request Artisan CLI 命令:
php artisan make:request StorePostRequest
生成的表单请求类将放置在 app/Http/Requests 目录中。如果该目录不存在,当你运行 make:request 命令时会自动创建。Laravel 生成的每个表单请求都有两个方法:authorize 和 rules。
正如你可能已经猜到的,authorize 方法负责确定当前已通过身份验证的用户是否可以执行该请求所代表的操作,而 rules 方法则返回应该应用于请求数据的验证规则:
/**
* 获取应用于该请求的验证规则。
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
];
}
[!注意]
你可以在rules方法的签名中对所需的任何依赖项进行类型提示。它们会通过 Laravel 服务容器自动解析。
那么,验证规则是如何被执行的呢?你只需要在控制器方法中对该请求进行类型提示即可。传入的表单请求会在控制器方法被调用之前进行验证,这意味着你不需要在控制器中加入任何验证逻辑:
/**
* 存储新的博客文章。
*/
public function store(StorePostRequest $request): RedirectResponse
{
// 传入的请求有效...
// 获取已验证的输入数据...
$validated = $request->validated();
// 获取已验证输入数据的一部分...
$validated = $request->safe()->only(['name', 'email']);
$validated = $request->safe()->except(['name', 'email']);
// 存储博客文章...
return redirect('/posts');
}
如果验证失败,将生成一个重定向响应,把用户发送回之前的位置。错误信息也会被闪存到 session 中,以便进行显示。如果该请求是 XHR 请求,则会向用户返回一个状态码为 422 的 HTTP 响应,其中包含验证错误的 JSON 表示。
[!注意]
需要为由 Inertia 驱动的 Laravel 前端添加实时表单请求验证吗?请查看 Laravel Precognition。
执行额外验证
有时,你需要在初始验证完成后执行额外的验证。你可以使用表单请求的 after 方法来实现这一点。
after 方法应返回一个可调用对象或闭包组成的数组,这些内容会在验证完成后被调用。给定的可调用对象会接收一个 Illuminate\Validation\Validator 实例,使你可以在必要时添加额外的错误消息:
use Illuminate\Validation\Validator;
/**
* 获取请求的“after”验证可调用对象。
*/
public function after(): array
{
return [
function (Validator $validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add(
'field',
'Something is wrong with this field!'
);
}
}
];
}
如前所述,after 方法返回的数组也可以包含可调用类。这些类的 __invoke 方法将接收一个 Illuminate\Validation\Validator 实例:
use App\Validation\ValidateShippingTime;
use App\Validation\ValidateUserStatus;
use Illuminate\Validation\Validator;
/**
* 获取请求的“after”验证可调用对象。
*/
public function after(): array
{
return [
new ValidateUserStatus,
new ValidateShippingTime,
function (Validator $validator) {
//
}
];
}
在第一次验证失败时停止
通过向你的请求类添加 StopOnFirstFailure 属性,你可以通知验证器,一旦发生一次验证失败,就应该停止验证所有属性:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\Attributes\StopOnFirstFailure;
use Illuminate\Foundation\Http\FormRequest;
#[StopOnFirstFailure]
class StorePostRequest extends FormRequest
{
// ...
}
遇到未知字段时失败
通过向你的请求类添加 FailOnUnknownFields 属性,你可以指示 Laravel 拒绝任何未在请求验证规则中定义的传入字段:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\Attributes\FailOnUnknownFields;
use Illuminate\Foundation\Http\FormRequest;
#[FailOnUnknownFields]
class StorePostRequest extends FormRequest
{
public function rules(): array
{
return [
'title' => ['required', 'string'],
'body' => ['required', 'string'],
];
}
}
你也可以在 AppServiceProvider 中为所有表单请求全局启用此行为:
use Illuminate\Foundation\Http\FormRequest;
/**
* 启动任何应用程序服务。
*/
public function boot(): void
{
FormRequest::failOnUnknownFields();
}
如果需要,你可以通过向该属性传递 false,为特定请求禁用此行为:
#[FailOnUnknownFields(false)]
class PublicWebhookRequest extends FormRequest
{
// ...
}
拒绝未知字段可以通过阻止意外的输入键进一步流入你的应用程序,为防止类似批量赋值的问题提供额外保护。不过,你仍然应该配置模型的 $fillable / $guarded 属性,并且只持久化可信的、经过验证的输入。
自定义重定向位置
当表单请求验证失败时,会生成一个重定向响应,将用户发送回之前的位置。不过,你可以自由自定义此行为。为此,你可以在表单请求上使用 RedirectTo 属性:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\Attributes\RedirectTo;
use Illuminate\Foundation\Http\FormRequest;
#[RedirectTo('/dashboard')]
class StorePostRequest extends FormRequest
{
// ...
}
或者,如果你希望将用户重定向到一个命名路由,可以改用 RedirectToRoute 属性:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\Attributes\RedirectToRoute;
use Illuminate\Foundation\Http\FormRequest;
#[RedirectToRoute('dashboard')]
class StorePostRequest extends FormRequest
{
// ...
}
自定义错误包
当表单请求验证失败时,错误会被闪存到 default 错误包中。如果你需要将错误存储到另一个命名错误包中,可以在表单请求上使用 ErrorBag 属性:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\Attributes\ErrorBag;
use Illuminate\Foundation\Http\FormRequest;
#[ErrorBag('login')]
class LoginRequest extends FormRequest
{
// ...
}
授权表单请求
表单请求类还包含一个 authorize 方法。在这个方法中,你可以判断已认证用户是否确实有权限更新某个给定资源。例如,你可以判断用户是否确实拥有他们正在尝试更新的博客评论。通常,你会在这个方法中与授权 Gate 和 Policy进行交互:
use App\Models\Comment;
/**
* 判断用户是否有权限发起此请求。
*/
public function authorize(): bool
{
$comment = Comment::find($this->route('comment'));
return $comment && $this->user()->can('update', $comment);
}
由于所有表单请求都继承自 Laravel 的基础请求类,因此我们可以使用 user 方法访问当前已认证的用户。另外,请注意上面示例中对 route 方法的调用。这个方法允许你访问当前被调用路由中定义的 URI 参数,例如下面示例中的 {comment} 参数:
Route::post('/comment/{comment}');
因此,如果你的应用程序使用了路由模型绑定,则可以通过将已解析的模型作为请求的属性来访问,从而让代码更加简洁:
return $this->user()->can('update', $this->comment);
如果 authorize 方法返回 false,Laravel 会自动返回一个状态码为 403 的 HTTP 响应,并且你的控制器方法不会执行。
如果你打算在应用程序的其他部分处理该请求的授权逻辑,可以完全删除 authorize 方法,或者直接返回 true:
/**
* 判断用户是否有权限发起此请求。
*/
public function authorize(): bool
{
return true;
}
[!注意]
你可以在authorize方法的签名中对所需的任何依赖项进行类型提示。它们会通过 Laravel 服务容器自动解析。
自定义错误消息
你可以通过重写 messages 方法来自定义表单请求所使用的错误消息。该方法应返回一个由属性 / 规则对及其对应错误消息组成的数组:
/**
* 获取已定义验证规则的错误消息。
*
* @return array<string, string>
*/
public function messages(): array
{
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}
自定义验证属性
Laravel 的许多内置验证规则错误消息中都包含一个 :attribute 占位符。如果你希望验证消息中的 :attribute 占位符被替换为自定义属性名称,可以通过重写 attributes 方法来指定自定义名称。该方法应返回一个由属性 / 名称对组成的数组:
/**
* 获取用于验证器错误的自定义属性。
*
* @return array<string, string>
*/
public function attributes(): array
{
return [
'email' => 'email address',
];
}
为验证准备输入
如果你需要在应用验证规则之前,对请求中的任何数据进行准备或清理,可以使用 prepareForValidation 方法:
use Illuminate\Support\Str;
/**
* 为验证准备数据。
*/
protected function prepareForValidation(): void
{
$this->merge([
'slug' => Str::slug($this->slug),
]);
}
同样,如果你需要在验证完成后规范化任何请求数据,可以使用 passedValidation 方法:
/**
* 处理一次通过的验证尝试。
*/
protected function passedValidation(): void
{
$this->replace(['name' => 'Taylor']);
}
手动创建验证器
如果你不想使用请求上的 validate 方法,可以使用 Validator 门面手动创建一个验证器实例。门面上的 make 方法会生成一个新的验证器实例:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
/**
* 存储新的博客文章。
*/
public function store(Request $request): RedirectResponse
{
$validator = Validator::make($request->all(), [
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
if ($validator->fails()) {
return redirect('/post/create')
->withErrors($validator)
->withInput();
}
// 获取已验证的输入...
$validated = $validator->validated();
// 获取已验证输入的一部分...
$validated = $validator->safe()->only(['name', 'email']);
$validated = $validator->safe()->except(['name', 'email']);
// 存储博客文章...
return redirect('/posts');
}
}
传递给 make 方法的第一个参数是要进行验证的数据。第二个参数是一个验证规则数组,这些规则将应用于该数据。
在确定请求验证是否失败之后,你可以使用 withErrors 方法将错误消息闪存到 session 中。使用此方法时,重定向之后 $errors 变量会自动与你的视图共享,从而使你能够轻松地将错误消息显示给用户。withErrors 方法接受验证器、MessageBag 或 PHP array。
在第一次验证失败时停止
stopOnFirstFailure 方法会通知验证器,一旦发生一次验证失败,就停止验证所有属性:
if ($validator->stopOnFirstFailure()->fails()) {
// ...
}
自动重定向
如果你想手动创建验证器实例,同时仍然利用 HTTP 请求的 validate 方法所提供的自动重定向功能,可以在现有的验证器实例上调用 validate 方法。如果验证失败,用户将被自动重定向;如果是 XHR 请求,则会返回 JSON 响应:
Validator::make($request->all(), [
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
])->validate();
如果验证失败,你可以使用 validateWithBag 方法将错误消息存储到一个命名错误包中:
Validator::make($request->all(), [
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
])->validateWithBag('post');
命名错误包
如果一个页面上有多个表单,你可能希望为包含验证错误的 MessageBag 命名,这样就可以获取特定表单的错误消息。要实现这一点,可以将名称作为第二个参数传递给 withErrors:
return redirect('/register')->withErrors($validator, 'login');
然后,你可以通过 $errors 变量访问已命名的 MessageBag 实例:
{{ $errors->login->first('email') }}
自定义错误消息
如果需要,你可以提供自定义错误消息,让验证器实例使用这些消息,而不是 Laravel 提供的默认错误消息。指定自定义消息有多种方式。首先,你可以将自定义消息作为第三个参数传递给 Validator::make 方法:
$validator = Validator::make($input, $rules, $messages = [
'required' => 'The :attribute field is required.',
]);
在这个示例中,:attribute 占位符会被替换为正在验证的字段的实际名称。你也可以在验证消息中使用其他占位符。例如:
$messages = [
'same' => 'The :attribute and :other must match.',
'size' => 'The :attribute must be exactly :size.',
'between' => 'The :attribute value :input is not between :min - :max.',
'in' => 'The :attribute must be one of the following types: :values',
];
为给定属性指定自定义消息
有时,你可能只希望为某个特定属性指定自定义错误消息。你可以使用“点”表示法来实现。先指定属性名称,然后再指定规则:
$messages = [
'email.required' => 'We need to know your email address!',
];
指定自定义属性值
Laravel 的许多内置错误消息都包含一个 :attribute 占位符,该占位符会被替换为正在验证的字段或属性名称。要自定义用于替换特定字段这些占位符的值,你可以将自定义属性数组作为第四个参数传递给 Validator::make 方法:
$validator = Validator::make($input, $rules, $messages, [
'email' => 'email address',
]);
执行额外验证
有时,你需要在初始验证完成后执行额外的验证。你可以使用验证器的 after 方法来实现这一点。after 方法接受一个闭包或一个可调用对象数组,这些内容会在验证完成后被调用。给定的可调用对象会接收一个 Illuminate\Validation\Validator 实例,使你可以在必要时添加额外的错误消息:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make(/* ... */);
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add(
'field', 'Something is wrong with this field!'
);
}
});
if ($validator->fails()) {
// ...
}
如前所述,after 方法也接受一个可调用对象数组。如果你的“验证后”逻辑被封装在可调用类中,这种方式尤其方便,这些类会通过它们的 __invoke 方法接收一个 Illuminate\Validation\Validator 实例:
use App\Validation\ValidateShippingTime;
use App\Validation\ValidateUserStatus;
$validator->after([
new ValidateUserStatus,
new ValidateShippingTime,
function ($validator) {
// ...
},
]);
使用已验证的输入
在使用表单请求或手动创建的验证器实例验证传入的请求数据后,你可能希望获取实际经过验证的传入请求数据。这可以通过多种方式实现。首先,你可以在表单请求或验证器实例上调用 validated 方法。该方法会返回一个包含已验证数据的数组:
$validated = $request->validated();
$validated = $validator->validated();
或者,你可以在表单请求或验证器实例上调用 safe 方法。该方法会返回一个 Illuminate\Support\ValidatedInput 实例。这个对象提供了 only、except 和 all 方法,用于获取已验证数据的子集或完整的已验证数据数组:
$validated = $request->safe()->only(['name', 'email']);
$validated = $request->safe()->except(['name', 'email']);
$validated = $request->safe()->all();
此外,Illuminate\Support\ValidatedInput 实例可以被遍历,也可以像数组一样进行访问:
// 可以遍历已验证的数据...
foreach ($request->safe() as $key => $value) {
// ...
}
// 可以像数组一样访问已验证的数据...
$validated = $request->safe();
$email = $validated['email'];
如果你希望向已验证的数据中添加额外字段,可以调用 merge 方法:
$validated = $request->safe()->merge(['name' => 'Taylor Otwell']);
如果你希望以集合实例的形式获取已验证的数据,可以调用 collect 方法:
$collection = $request->safe()->collect();
处理错误消息
在 Validator 实例上调用 errors 方法后,你将获得一个 Illuminate\Support\MessageBag 实例,该实例提供了多种用于处理错误消息的便捷方法。自动提供给所有视图的 $errors 变量同样也是 MessageBag 类的实例。
获取某个字段的第一条错误消息
要获取给定字段的第一条错误消息,可以使用 first 方法:
$errors = $validator->errors();
echo $errors->first('email');
获取某个字段的所有错误消息
如果你需要获取给定字段的所有错误消息数组,可以使用 get 方法:
foreach ($errors->get('email') as $message) {
// ...
}
如果你正在验证一个数组表单字段,可以使用 * 字符获取数组中每个元素的所有错误消息:
foreach ($errors->get('attachments.*') as $message) {
// ...
}
获取所有字段的所有错误消息
要获取所有字段的所有错误消息数组,请使用 all 方法:
foreach ($errors->all() as $message) {
// ...
}
判断某个字段是否存在错误消息
可以使用 has 方法来判断给定字段是否存在任何错误消息:
if ($errors->has('email')) {
// ...
}
在语言文件中指定自定义消息
Laravel 的每个内置验证规则都有一条错误消息,这些消息位于应用程序的 lang/en/validation.php 文件中。如果你的应用程序没有 lang 目录,可以使用 lang:publish Artisan 命令让 Laravel 创建它。
在 lang/en/validation.php 文件中,你会找到每个验证规则对应的翻译条目。你可以根据应用程序的需求自由更改或修改这些消息。
此外,你可以将此文件复制到其他语言目录中,以便将消息翻译成应用程序所使用的语言。要了解更多关于 Laravel 本地化的信息,请查看完整的本地化文档。
[!警告]
默认情况下,Laravel 应用程序骨架不包含lang目录。如果你想自定义 Laravel 的语言文件,可以通过lang:publishArtisan 命令发布它们。
针对特定属性的自定义消息
你可以在应用程序的验证语言文件中,自定义指定属性与规则组合所使用的错误消息。为此,请将你的自定义消息添加到应用程序 lang/xx/validation.php 语言文件的 custom 数组中:
'custom' => [
'email' => [
'required' => 'We need to know your email address!',
'max' => 'Your email address is too long!'
],
],
在语言文件中指定属性
Laravel 的许多内置错误消息都包含一个 :attribute 占位符,该占位符会被替换为正在验证的字段或属性名称。如果你希望验证消息中的 :attribute 部分被替换为自定义值,可以在 lang/xx/validation.php 语言文件的 attributes 数组中指定自定义属性名称:
'attributes' => [
'email' => 'email address',
],
[!警告]
默认情况下,Laravel 应用程序骨架不包含lang目录。如果你想自定义 Laravel 的语言文件,可以通过lang:publishArtisan 命令发布它们。
在语言文件中指定值
Laravel 的一些内置验证规则错误消息中包含一个 :value 占位符,该占位符会被替换为请求属性的当前值。不过,有时你可能需要将验证消息中的 :value 部分替换为该值的自定义表示形式。例如,考虑以下规则,它指定当 payment_type 的值为 cc 时,必须提供信用卡号码:
Validator::make($request->all(), [
'credit_card_number' => ['required_if:payment_type,cc']
]);
如果该验证规则失败,将生成以下错误消息:
The credit card number field is required when payment type is cc.
你可以不将 cc 显示为支付类型的值,而是在 lang/xx/validation.php 语言文件中通过定义一个 values 数组,指定一个更友好的值表示形式:
'values' => [
'payment_type' => [
'cc' => 'credit card'
],
],
[!警告]
默认情况下,Laravel 应用程序骨架不包含lang目录。如果你想自定义 Laravel 的语言文件,可以通过lang:publishArtisan 命令发布它们。
定义此值后,验证规则将生成以下错误消息:
The credit card number field is required when payment type is credit card.
可用的验证规则
下面列出了所有可用的验证规则及其功能:
布尔值
字符串
有效 URL
字母
字母、数字、短横线和下划线
字母和数字
ASCII
确认
当前密码
不同
不能以指定值开头
不能以指定值结尾
电子邮件
以指定值结尾
枚举
十六进制颜色
在指定值中
IP 地址
JSON
小写
MAC 地址
最大值
最小值
不在指定值中
正则表达式
非正则表达式
相同
大小
以指定值开头
字符串
大写
URL
ULID
UUID
数字
数组
日期
文件
数据库
实用工具
任意一个
遇错即停
排除
条件排除
除非满足条件否则排除
与指定字段同时存在时排除
缺少指定字段时排除
已填写
缺失
条件缺失
除非满足条件否则缺失
与指定字段同时存在时缺失
与所有指定字段同时存在时缺失
可为空
存在
条件存在
除非满足条件否则存在
与指定字段同时存在时存在
与所有指定字段同时存在时存在
禁止
条件禁止
条件接受时禁止
条件拒绝时禁止
除非满足条件否则禁止
禁止其他字段
必填
条件必填
条件接受时必填
条件拒绝时必填
除非满足条件否则必填
与指定字段同时存在时必填
与所有指定字段同时存在时必填
缺少指定字段时必填
缺少所有指定字段时必填
必需的数组键
有时
accepted
正在验证的字段必须为 "yes"、"on"、1、"1"、true 或 "true"。这对于验证“服务条款”的接受情况或类似字段非常有用。
accepted_if:anotherfield,value,...
如果另一个正在验证的字段等于指定值,则当前正在验证的字段必须为 "yes"、"on"、1、"1"、true 或 "true"。这对于验证“服务条款”的接受情况或类似字段非常有用。
active_url
根据 PHP 的 dns_get_record 函数,正在验证的字段必须具有有效的 A 或 AAAA 记录。在将提供的 URL 传递给 dns_get_record 之前,会先使用 PHP 的 parse_url 函数提取其主机名。
after:date
正在验证的字段必须是晚于给定日期的值。日期会被传递给 PHP 的 strtotime 函数,以转换为有效的 DateTime 实例:
'start_date' => ['required', 'date', 'after:tomorrow']
除了传递一个由 strtotime 解析的日期字符串之外,你还可以指定另一个字段,与该日期进行比较:
'finish_date' => ['required', 'date', 'after:start_date']
为方便起见,可以使用流式的 date 规则构建器来构建基于日期的规则:
use Illuminate\Validation\Rule;
'start_date' => [
'required',
Rule::date()->after(today()->addDays(7)),
],
afterToday 和 todayOrAfter 方法可用于以流式方式分别表示日期必须晚于今天,或等于今天或晚于今天:
'start_date' => [
'required',
Rule::date()->afterToday(),
],
after_or_equal:date
正在验证的字段必须是晚于或等于给定日期的值。有关更多信息,请参阅 after 规则。
为方便起见,可以使用流式的 date 规则构建器来构建基于日期的规则:
use Illuminate\Validation\Rule;
'start_date' => [
'required',
Rule::date()->afterOrEqual(today()->addDays(7)),
],
anyOf
Rule::anyOf 验证规则允许你指定正在验证的字段必须满足给定验证规则集中的任意一个。例如,下面的规则将验证 username 字段要么是一个电子邮件地址,要么是一个至少 6 个字符长的字母数字字符串(包括短横线):
use Illuminate\Validation\Rule;
'username' => [
'required',
Rule::anyOf([
['string', 'email'],
['string', 'alpha_dash', 'min:6'],
]),
],
alpha
正在验证的字段必须完全由 Unicode 字母字符组成,这些字符包含在 \p{L} 和 \p{M} 中。
要将此验证规则限制为 ASCII 范围内的字符(a-z 和 A-Z),可以向验证规则提供 ascii 选项:
'username' => ['alpha:ascii'],
alpha_dash
正在验证的字段必须完全由 Unicode 字母数字字符组成,这些字符包含在 \p{L}、\p{M}、\p{N} 中,以及 ASCII 短横线(-)和 ASCII 下划线(_)。
要将此验证规则限制为 ASCII 范围内的字符(a-z、A-Z 和 0-9),可以向验证规则提供 ascii 选项:
'username' => ['alpha_dash:ascii'],
alpha_num
正在验证的字段必须完全由 Unicode 字母数字字符组成,这些字符包含在 \p{L}、\p{M} 和 \p{N} 中。
要将此验证规则限制为 ASCII 范围内的字符(a-z、A-Z 和 0-9),可以向验证规则提供 ascii 选项:
'username' => ['alpha_num:ascii'],
array
正在验证的字段必须是一个 PHP array。
当向 array 规则提供额外值时,输入数组中的每个键都必须存在于提供给该规则的值列表中。在下面的示例中,输入数组中的 admin 键是无效的,因为它不包含在提供给 array 规则的值列表中:
use Illuminate\Support\Facades\Validator;
$input = [
'user' => [
'name' => 'Taylor Otwell',
'username' => 'taylorotwell',
'admin' => true,
],
];
Validator::make($input, [
'user' => ['array:name,username'],
]);
一般来说,你应该始终指定允许存在于数组中的数组键。
ascii
正在验证的字段必须完全由 7 位 ASCII 字符组成。
bail
在第一次验证失败后,停止运行该字段的验证规则。
虽然 bail 规则只会在遇到验证失败时停止验证特定字段,但 stopOnFirstFailure 方法会通知验证器,一旦发生一次验证失败,就停止验证所有属性:
if ($validator->stopOnFirstFailure()->fails()) {
// ...
}
before:date
正在验证的字段必须是早于给定日期的值。日期会被传递给 PHP 的 strtotime 函数,以转换为有效的 DateTime 实例。此外,与 after 规则一样,也可以将另一个正在验证的字段名称作为 date 的值。
为方便起见,基于日期的规则也可以使用流式的 date 规则构建器来构建:
use Illuminate\Validation\Rule;
'start_date' => [
'required',
Rule::date()->before(today()->subDays(7)),
],
beforeToday 和 todayOrBefore 方法可以分别以流式方式表示日期必须早于今天,或等于今天或早于今天:
'start_date' => [
'required',
Rule::date()->beforeToday(),
],
before_or_equal:date
正在验证的字段必须是早于或等于给定日期的值。日期会被传递给 PHP 的 strtotime 函数,以转换为有效的 DateTime 实例。此外,与 after 规则一样,也可以将另一个正在验证的字段名称作为 date 的值。
为方便起见,基于日期的规则也可以使用流式的 date 规则构建器来构建:
use Illuminate\Validation\Rule;
'start_date' => [
'required',
Rule::date()->beforeOrEqual(today()->subDays(7)),
],
between:min,max
正在验证的字段大小必须介于给定的 min 和 max 之间(包含边界值)。字符串、数值、数组和文件的判断方式与 size 规则相同。
boolean
正在验证的字段必须能够转换为布尔值。可接受的输入包括 true、false、1、0、"1" 和 "0"。
你可以使用 strict 参数,使字段只有在其值为 true 或 false 时才被视为有效:
'foo' => ['boolean:strict']
confirmed
正在验证的字段必须存在一个与之匹配的 {field}_confirmation 字段。例如,如果正在验证的字段是 password,那么输入中必须存在一个与其匹配的 password_confirmation 字段。
你也可以传入一个自定义的确认字段名称。例如,confirmed:repeat_username 将要求 repeat_username 字段与正在验证的字段相匹配。
contains:foo,bar,...
正在验证的字段必须是一个数组,并且包含所有给定的参数值。由于此规则通常需要你对数组使用 implode,因此可以使用 Rule::contains 方法以流式方式构建该规则:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($data, [
'roles' => [
'required',
'array',
Rule::contains(['admin', 'editor']),
],
]);
doesnt_contain:foo,bar,...
正在验证的字段必须是一个数组,并且不包含任何给定的参数值。由于此规则通常需要你对数组使用 implode,因此可以使用 Rule::doesntContain 方法以流式方式构建该规则:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($data, [
'roles' => [
'required',
'array',
Rule::doesntContain(['admin', 'editor']),
],
]);
current_password
正在验证的字段必须与已认证用户的密码匹配。你可以使用该规则的第一个参数指定一个身份验证守卫:
'password' => ['current_password:api']
date
根据 PHP 的 strtotime 函数,正在验证的字段必须是一个有效的、非相对日期。
date_equals:date
正在验证的字段必须等于给定日期。日期会被传递给 PHP 的 strtotime 函数,以转换为有效的 DateTime 实例。
date_format:format,...
正在验证的字段必须匹配给定的 formats 中的一个。验证字段时,你应该使用 date 或 date_format,而不是同时使用两者。此验证规则支持 PHP DateTime 类支持的所有格式。
For convenience, date-based rules may be constructed using the fluent date rule builder:
use Illuminate\Validation\Rule;
'start_date' => [
'required',
Rule::date()->format('Y-m-d'),
],
decimal:min,max
The field under validation must be numeric and must contain the specified number of decimal places:
// Must have exactly two decimal places (9.99)...
'price' => ['decimal:2']
// Must have between 2 and 4 decimal places...
'price' => ['decimal:2,4']
declined
The field under validation must be "no", "off", 0, "0", false, or "false".
declined_if:anotherfield,value,...
The field under validation must be "no", "off", 0, "0", false, or "false" if another field under validation is equal to a specified value.
different:field
The field under validation must have a different value than field.
digits:value
The integer under validation must have an exact length of value.
digits_between:min,max
The integer under validation must have a length between the given min and max.
dimensions
The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters:
'avatar' => ['dimensions:min_width=100,min_height=200']
Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio, min_ratio, max_ratio.
A ratio constraint should be represented as width divided by height. This can be specified either by a fraction like 3/2 or a float like 1.5:
'avatar' => ['dimensions:ratio=3/2']
The min_ratio and max_ratio constraints may be used to define a range of acceptable aspect ratios:
'avatar' => ['dimensions:min_ratio=1/2,max_ratio=3/2']
Since this rule requires several arguments, it is often more convenient to use the Rule::dimensions method to fluently construct the rule:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($data, [
'avatar' => [
'required',
Rule::dimensions()
->maxWidth(1000)
->maxHeight(500)
->ratio(3 / 2),
],
]);
You may also use the minRatio, maxRatio, and ratioBetween methods to fluently define ratio constraints:
Rule::dimensions()->ratioBetween(min: 1 / 2, max: 3 / 2)
distinct
When validating arrays, the field under validation must not have any duplicate values:
'foo.*.id' => ['distinct']
Distinct uses loose variable comparisons by default. To use strict comparisons, you may add the strict parameter to your validation rule definition:
'foo.*.id' => ['distinct:strict']
You may add ignore_case to the validation rule's arguments to make the rule ignore capitalization differences:
'foo.*.id' => ['distinct:ignore_case']
doesnt_start_with:foo,bar,...
The field under validation must not start with one of the given values.
doesnt_end_with:foo,bar,...
The field under validation must not end with one of the given values.
The field under validation must be formatted as an email address. This validation rule utilizes the egulias/email-validator package for validating the email address. By default, the RFCValidation validator is applied, but you can apply other validation styles as well:
'email' => ['email:rfc,dns']
The example above will apply the RFCValidation and DNSCheckValidation validations. Here's a full list of validation styles you can apply:
rfc:RFCValidation- Validate the email address according to supported RFCs.strict:NoRFCWarningsValidation- Validate the email according to supported RFCs, failing when warnings are found (e.g. trailing periods and multiple consecutive periods).dns:DNSCheckValidation- Ensure the email address's domain has a valid MX record.spoof:SpoofCheckValidation- Ensure the email address does not contain homograph or deceptive Unicode characters.filter:FilterEmailValidation- Ensure the email address is valid according to PHP'sfilter_varfunction.filter_unicode:FilterEmailValidation::unicode()- Ensure the email address is valid according to PHP'sfilter_varfunction, allowing some Unicode characters.
For convenience, email validation rules may be built using the fluent rule builder:
use Illuminate\Validation\Rule;
$request->validate([
'email' => [
'required',
Rule::email()
->rfcCompliant(strict: false)
->validateMxRecord()
->preventSpoofing()
],
]);
[!WARNING]
Thednsandspoofvalidators require the PHPintlextension.
encoding:encoding_type
The field under validation must match the specified character encoding. This rule uses PHP's mb_check_encoding function to verify the encoding of the given file or string value. For convenience, the encoding rule may be constructed using Laravel's fluent file rule builder:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\File;
Validator::validate($input, [
'attachment' => [
'required',
File::types(['csv'])
->encoding('utf-8'),
],
]);
ends_with:foo,bar,...
The field under validation must end with one of the given values.
enum
The Enum rule is a class-based rule that validates whether the field under validation contains a valid enum value. The Enum rule accepts the name of the enum as its only constructor argument. When validating primitive values, a backed Enum should be provided to the Enum rule:
use App\Enums\ServerStatus;
use Illuminate\Validation\Rule;
$request->validate([
'status' => [Rule::enum(ServerStatus::class)],
]);
The Enum rule's only and except methods may be used to limit which enum cases should be considered valid:
Rule::enum(ServerStatus::class)
->only([ServerStatus::Pending, ServerStatus::Active]);
Rule::enum(ServerStatus::class)
->except([ServerStatus::Pending, ServerStatus::Active]);
The when method may be used to conditionally modify the Enum rule:
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
Rule::enum(ServerStatus::class)
->when(
Auth::user()->isAdmin(),
fn ($rule) => $rule->only(...),
fn ($rule) => $rule->only(...),
);
exclude
The field under validation will be excluded from the request data returned by the validate and validated methods.
exclude_if:anotherfield,value
The field under validation will be excluded from the request data returned by the validate and validated methods if the anotherfield field is equal to value.
If complex conditional exclusion logic is required, you may utilize the Rule::excludeIf method. This method accepts a boolean or a closure. When given a closure, the closure should return true or false to indicate if the field under validation should be excluded:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($request->all(), [
'role_id' => [Rule::excludeIf($request->user()->is_admin)],
]);
Validator::make($request->all(), [
'role_id' => [Rule::excludeIf(fn () => $request->user()->is_admin)],
]);
exclude_unless:anotherfield,value
The field under validation will be excluded from the request data returned by the validate and validated methods unless anotherfield's field is equal to value. If value is null (exclude_unless:name,null), the field under validation will be excluded unless the comparison field is null or the comparison field is missing from the request data.
If complex conditional exclusion logic is required, you may utilize the Rule::excludeUnless method. This method accepts a boolean or a closure. When given a closure, the closure should return true or false to indicate if the field under validation should not be excluded:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($request->all(), [
'role_id' => [Rule::excludeUnless($request->user()->is_admin)],
]);
Validator::make($request->all(), [
'role_id' => [Rule::excludeUnless(fn () => $request->user()->is_admin)],
]);
exclude_with:anotherfield
The field under validation will be excluded from the request data returned by the validate and validated methods if the anotherfield field is present.
exclude_without:anotherfield
The field under validation will be excluded from the request data returned by the validate and validated methods if the anotherfield field is not present.
exists:table,column
The field under validation must exist in a given database table.
Basic Usage of Exists Rule
'state' => ['exists:states']
If the column option is not specified, the field name will be used. So, in this case, the rule will validate that the states database table contains a record with a state column value matching the request's state attribute value.
Specifying a Custom Column Name
You may explicitly specify the database column name that should be used by the validation rule by placing it after the database table name:
'state' => ['exists:states,abbreviation']
Occasionally, you may need to specify a specific database connection to be used for the exists query. You can accomplish this by prepending the connection name to the table name:
'email' => ['exists:connection.staff,email']
Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:
'user_id' => ['exists:App\Models\User,id']
If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule.
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::exists('staff')->where(function (Builder $query) {
$query->where('account_id', 1);
}),
],
]);
You may explicitly specify the database column name that should be used by the exists rule generated by the Rule::exists method by providing the column name as the second argument to the exists method:
'state' => [Rule::exists('states', 'abbreviation')],
Sometimes, you may wish to validate whether an array of values exists in the database. You can do so by adding both the exists and array rules to the field being validated:
'states' => ['array', Rule::exists('states', 'abbreviation')],
When both of these rules are assigned to a field, Laravel will automatically build a single query to determine if all of the given values exist in the specified table.
extensions:foo,bar,...
The file under validation must have a user-assigned extension corresponding to one of the listed extensions:
'photo' => ['required', 'extensions:jpg,png'],
[!WARNING]
You should never rely on validating a file by its user-assigned extension alone. This rule should typically always be used in combination with the mimes or mimetypes rules.
file
The field under validation must be a successfully uploaded file.
filled
The field under validation must not be empty when it is present.
gt:field
The field under validation must be greater than the given field or value. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.
gte:field
The field under validation must be greater than or equal to the given field or value. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.
hex_color
The field under validation must contain a valid color value in hexadecimal format.
image
The file under validation must be an image (jpg, jpeg, png, bmp, gif, or webp).
[!WARNING]
By default, the image rule does not allow SVG files due to the possibility of XSS vulnerabilities. If you need to allow SVG files, you may provide theallow_svgdirective to theimagerule (image:allow_svg).
in:foo,bar,...
The field under validation must be included in the given list of values. Since this rule often requires you to implode an array, the Rule::in method may be used to fluently construct the rule:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($data, [
'zones' => [
'required',
Rule::in(['first-zone', 'second-zone']),
],
]);
When the in rule is combined with the array rule, each value in the input array must be present within the list of values provided to the in rule. In the following example, the LAS airport code in the input array is invalid since it is not contained in the list of airports provided to the in rule:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
$input = [
'airports' => ['NYC', 'LAS'],
];
Validator::make($input, [
'airports' => [
'required',
'array',
],
'airports.*' => Rule::in(['NYC', 'LIT']),
]);
in_array:anotherfield.*
The field under validation must exist in anotherfield's values.
in_array_keys:value.*
The field under validation must be an array having at least one of the given values as a key within the array:
'config' => ['array', 'in_array_keys:timezone']
integer
The field under validation must be an integer.
You may use the strict parameter to only consider the field valid if its type is integer. Strings with integer values will be considered invalid:
'age' => ['integer:strict']
[!WARNING]
This validation rule does not verify that the input is of the "integer" variable type, only that the input is of a type accepted by PHP'sFILTER_VALIDATE_INTrule. If you need to validate the input as being a number please use this rule in combination with thenumericvalidation rule.
ip
The field under validation must be an IP address.
ipv4
The field under validation must be an IPv4 address.
ipv6
The field under validation must be an IPv6 address.
json
The field under validation must be a valid JSON string.
lt:field
The field under validation must be less than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.
lte:field
The field under validation must be less than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.
lowercase
The field under validation must be lowercase.
list
The field under validation must be an array that is a list. An array is considered a list if its keys consist of consecutive numbers from 0 to count($array) - 1.
mac_address
The field under validation must be a MAC address.
max:value
The field under validation must be less than or equal to a maximum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.
max_digits:value
The integer under validation must have a maximum length of value.
mimetypes:text/plain,...
The file under validation must match one of the given MIME types:
'video' => ['mimetypes:video/avi,video/mpeg,video/quicktime'],
'media' => ['mimetypes:image/*,video/*'],
To determine the MIME type of the uploaded file, the file's contents will be read and the framework will attempt to guess the MIME type, which may be different from the client's provided MIME type.
mimes:foo,bar,...
The file under validation must have a MIME type corresponding to one of the listed extensions:
'photo' => ['mimes:jpg,bmp,png']
Even though you only need to specify the extensions, this rule actually validates the MIME type of the file by reading the file's contents and guessing its MIME type. A full listing of MIME types and their corresponding extensions may be found at the following location:
svn.apache.org/repos/asf/httpd/htt...
MIME Types and Extensions
This validation rule does not verify agreement between the MIME type and the extension the user assigned to the file. For example, the mimes:png validation rule would consider a file containing valid PNG content to be a valid PNG image, even if the file is named photo.txt. If you would like to validate the user-assigned extension of the file, you may use the extensions rule.
min:value
The field under validation must have a minimum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.
min_digits:value
The integer under validation must have a minimum length of value.
multiple_of:value
The field under validation must be a multiple of value.
missing
The field under validation must not be present in the input data.
missing_if:anotherfield,value,...
The field under validation must not be present if the anotherfield field is equal to any value.
missing_unless:anotherfield,value
The field under validation must not be present unless the anotherfield field is equal to any value.
missing_with:foo,bar,...
The field under validation must not be present only if any of the other specified fields are present.
missing_with_all:foo,bar,...
The field under validation must not be present only if all of the other specified fields are present.
not_in:foo,bar,...
The field under validation must not be included in the given list of values. The Rule::notIn method may be used to fluently construct the rule:
use Illuminate\Validation\Rule;
Validator::make($data, [
'toppings' => [
'required',
Rule::notIn(['sprinkles', 'cherries']),
],
]);
not_regex:pattern
The field under validation must not match the given regular expression.
Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => ['not_regex:/^.+$/i'].
nullable
The field under validation may be null.
numeric
The field under validation must be numeric.
You may use the strict parameter to only consider the field valid if its value is an integer or float type. Numeric strings will be considered invalid:
'amount' => ['numeric:strict']
present
The field under validation must exist in the input data.
present_if:anotherfield,value,...
The field under validation must be present if the anotherfield field is equal to any value.
present_unless:anotherfield,value
The field under validation must be present unless the anotherfield field is equal to any value.
present_with:foo,bar,...
The field under validation must be present only if any of the other specified fields are present.
present_with_all:foo,bar,...
The field under validation must be present only if all of the other specified fields are present.
prohibited
The field under validation must be missing or empty. A field is "empty" if it meets one of the following criteria:
- The value is
null. - The value is an empty string.
- The value is an empty array or empty
Countableobject. - The value is an uploaded file with an empty path.
prohibited_if:anotherfield,value,...
The field under validation must be missing or empty if the anotherfield field is equal to any value. A field is "empty" if it meets one of the following criteria:
- The value is
null. - The value is an empty string.
- The value is an empty array or empty
Countableobject. - The value is an uploaded file with an empty path.
If complex conditional prohibition logic is required, you may utilize the Rule::prohibitedIf method. This method accepts a boolean or a closure. When given a closure, the closure should return true or false to indicate if the field under validation should be prohibited:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($request->all(), [
'role_id' => [Rule::prohibitedIf($request->user()->is_admin)],
]);
Validator::make($request->all(), [
'role_id' => [Rule::prohibitedIf(fn () => $request->user()->is_admin)],
]);
prohibited_if_accepted:anotherfield,...
The field under validation must be missing or empty if the anotherfield field is equal to "yes", "on", 1, "1", true, or "true".
prohibited_if_declined:anotherfield,...
The field under validation must be missing or empty if the anotherfield field is equal to "no", "off", 0, "0", false, or "false".
prohibited_unless:anotherfield,value,...
The field under validation must be missing or empty unless the anotherfield field is equal to any value. A field is "empty" if it meets one of the following criteria:
- The value is
null. - The value is an empty string.
- The value is an empty array or empty
Countableobject. - The value is an uploaded file with an empty path.
If complex conditional prohibition logic is required, you may utilize the Rule::prohibitedUnless method. This method accepts a boolean or a closure. When given a closure, the closure should return true or false to indicate if the field under validation should not be prohibited:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($request->all(), [
'role_id' => [Rule::prohibitedUnless($request->user()->is_admin)],
]);
Validator::make($request->all(), [
'role_id' => [Rule::prohibitedUnless(fn () => $request->user()->is_admin)],
]);
prohibits:anotherfield,...
If the field under validation is not missing or empty, all fields in anotherfield must be missing or empty. A field is "empty" if it meets one of the following criteria:
- The value is
null. - The value is an empty string.
- The value is an empty array or empty
Countableobject. - The value is an uploaded file with an empty path.
regex:pattern
The field under validation must match the given regular expression.
Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => ['regex:/^.+@.+$/i'].
required
The field under validation must be present in the input data and not empty. A field is "empty" if it meets one of the following criteria:
- The value is
null. - The value is an empty string.
- The value is an empty array or empty
Countableobject. - The value is an uploaded file with no path.
required_if:anotherfield,value,...
The field under validation must be present and not empty if the anotherfield field is equal to any value.
If you would like to construct a more complex condition for the required_if rule, you may use the Rule::requiredIf method. This method accepts a boolean or a closure. When passed a closure, the closure should return true or false to indicate if the field under validation is required:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($request->all(), [
'role_id' => [Rule::requiredIf($request->user()->is_admin)],
]);
Validator::make($request->all(), [
'role_id' => [Rule::requiredIf(fn () => $request->user()->is_admin)],
]);
required_if_accepted:anotherfield,...
The field under validation must be present and not empty if the anotherfield field is equal to "yes", "on", 1, "1", true, or "true".
required_if_declined:anotherfield,...
The field under validation must be present and not empty if the anotherfield field is equal to "no", "off", 0, "0", false, or "false".
required_unless:anotherfield,value,...
The field under validation must be present and not empty unless the anotherfield field is equal to any value. This also means anotherfield must be present in the request data unless value is null. If value is null (required_unless:name,null), the field under validation will be required unless the comparison field is null or the comparison field is missing from the request data.
If you would like to construct a more complex condition for the required_unless rule, you may use the Rule::requiredUnless method. This method accepts a boolean or a closure. When passed a closure, the closure should return true or false to indicate if the field under validation is not required:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($request->all(), [
'role_id' => [Rule::requiredUnless($request->user()->is_admin)],
]);
Validator::make($request->all(), [
'role_id' => [Rule::requiredUnless(fn () => $request->user()->is_admin)],
]);
required_with:foo,bar,...
The field under validation must be present and not empty only if any of the other specified fields are present and not empty.
required_with_all:foo,bar,...
The field under validation must be present and not empty only if all of the other specified fields are present and not empty.
required_without:foo,bar,...
The field under validation must be present and not empty only when any of the other specified fields are empty or not present.
required_without_all:foo,bar,...
The field under validation must be present and not empty only when all of the other specified fields are empty or not present.
required_array_keys:foo,bar,...
The field under validation must be an array and must contain at least the specified keys.
same:field
The given field must match the field under validation.
size:value
The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value (the attribute must also have the numeric or integer rule). For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes. Let's look at some examples:
// Validate that a string is exactly 12 characters long...
'title' => ['size:12'];
// Validate that a provided integer equals 10...
'seats' => ['integer', 'size:10'];
// Validate that an array has exactly 5 elements...
'tags' => ['array', 'size:5'];
// Validate that an uploaded file is exactly 512 kilobytes...
'image' => ['file', 'size:512'];
starts_with:foo,bar,...
The field under validation must start with one of the given values.
string
The field under validation must be a string. If you would like to allow the field to also be null, you should assign the nullable rule to the field.
For convenience, string validation rules may also be constructed using the fluent Rule::string() rule builder:
use Illuminate\Validation\Rule;
'title' => [
'required',
Rule::string()
->min(3)
->max(255)
->alphaDash(ascii: true),
],
The string rule builder provides methods for common string constraints, including alpha, alphaDash, alphaNumeric, ascii, between, doesntEndWith, doesntStartWith, endsWith, exactly, lowercase, max, min, startsWith, and uppercase. Since the rule builder is conditionable, you may also use the when and unless methods to conditionally apply constraints.
timezone
The field under validation must be a valid timezone identifier according to the DateTimeZone::listIdentifiers method.
The arguments accepted by the DateTimeZone::listIdentifiers method may also be provided to this validation rule:
'timezone' => ['required', 'timezone:all'];
'timezone' => ['required', 'timezone:Africa'];
'timezone' => ['required', 'timezone:per_country,US'];
unique:table,column
The field under validation must not exist within the given database table.
Specifying a Custom Table / Column Name:
Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:
'email' => ['unique:App\Models\User,email_address']
The column option may be used to specify the field's corresponding database column. If the column option is not specified, the name of the field under validation will be used.
'email' => ['unique:users,email_address']
Specifying a Custom Database Connection
Occasionally, you may need to set a custom connection for database queries made by the Validator. To accomplish this, you may prepend the connection name to the table name:
'email' => ['unique:connection.users,email_address']
Forcing a Unique Rule to Ignore a Given ID:
Sometimes, you may wish to ignore a given ID during unique validation. For example, consider an "update profile" screen that includes the user's name, email address, and location. You will probably want to verify that the email address is unique. However, if the user only changes the name field and not the email field, you do not want a validation error to be thrown because the user is already the owner of the email address in question.
To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule.
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
[!WARNING]
You should never pass any user controlled request input into theignoremethod. Instead, you should only pass a system generated unique ID such as an auto-incrementing ID or UUID from an Eloquent model instance. Otherwise, your application will be vulnerable to an SQL injection attack.
Instead of passing the model key's value to the ignore method, you may also pass the entire model instance. Laravel will automatically extract the key from the model:
Rule::unique('users')->ignore($user)
If your table uses a primary key column name other than id, you may specify the name of the column when calling the ignore method:
Rule::unique('users')->ignore($user->id, 'user_id')
By default, the unique rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the unique method:
Rule::unique('users', 'email_address')->ignore($user->id)
Adding Additional Where Clauses:
You may specify additional query conditions by customizing the query using the where method. For example, let's add a query condition that scopes the query to only search records that have an account_id column value of 1:
'email' => Rule::unique('users')->where(fn (Builder $query) => $query->where('account_id', 1))
Ignoring Soft Deleted Records in Unique Checks:
By default, the unique rule includes soft deleted records when determining uniqueness. To exclude soft deleted records from the uniqueness check, you may invoke the withoutTrashed method:
Rule::unique('users')->withoutTrashed();
If your model uses a column name other than deleted_at for soft deleted records, you may provide the column name when invoking the withoutTrashed method:
Rule::unique('users')->withoutTrashed('was_deleted_at');
uppercase
The field under validation must be uppercase.
url
The field under validation must be a valid URL.
If you would like to specify the URL protocols that should be considered valid, you may pass the protocols as validation rule parameters:
'url' => ['url:http,https'],
'game' => ['url:minecraft,steam'],
ulid
The field under validation must be a valid Universally Unique Lexicographically Sortable Identifier (ULID).
uuid
The field under validation must be a valid RFC 9562 (version 1, 3, 4, 5, 6, 7, or 8) universally unique identifier (UUID).
You may also validate that the given UUID matches a UUID specification by version:
'uuid' => ['uuid:4']
Conditionally Adding Rules
Skipping Validation When Fields Have Certain Values
You may occasionally wish to not validate a given field if another field has a given value. You may accomplish this using the exclude_if validation rule. In this example, the appointment_date and doctor_name fields will not be validated if the has_appointment field has a value of false:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($data, [
'has_appointment' => ['required', 'boolean'],
'appointment_date' => ['exclude_if:has_appointment,false', 'required', 'date'],
'doctor_name' => ['exclude_if:has_appointment,false', 'required', 'string'],
]);
Alternatively, you may use the exclude_unless rule to not validate a given field unless another field has a given value:
$validator = Validator::make($data, [
'has_appointment' => ['required', 'boolean'],
'appointment_date' => ['exclude_unless:has_appointment,true', 'required', 'date'],
'doctor_name' => ['exclude_unless:has_appointment,true', 'required', 'string'],
]);
Validating When Present
In some situations, you may wish to run validation checks against a field only if that field is present in the data being validated. To quickly accomplish this, add the sometimes rule to your rule list:
$validator = Validator::make($data, [
'email' => ['sometimes', 'required', 'email'],
]);
In the example above, the email field will only be validated if it is present in the $data array.
[!NOTE]
If you are attempting to validate a field that should always be present but may be empty, check out this note on optional fields.
Complex Conditional Validation
Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present. Adding these validation rules doesn't have to be a pain. First, create a Validator instance with your static rules that never change:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'email' => ['required', 'email'],
'games' => ['required', 'integer', 'min:0'],
]);
Let's assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game resale shop, or maybe they just enjoy collecting games. To conditionally add this requirement, we can use the sometimes method on the Validator instance.
use Illuminate\Support\Fluent;
$validator->sometimes('reason', ['required', 'max:500'], function (Fluent $input) {
return $input->games >= 100;
});
The first argument passed to the sometimes method is the name of the field we are conditionally validating. The second argument is a list of the rules we want to add. If the closure passed as the third argument returns true, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once:
$validator->sometimes(['reason', 'cost'], 'required', function (Fluent $input) {
return $input->games >= 100;
});
[!NOTE]
The$inputparameter passed to your closure will be an instance ofIlluminate\Support\Fluentand may be used to access your input and files under validation.
Complex Conditional Array Validation
Sometimes you may want to validate a field based on another field in the same nested array whose index you do not know. In these situations, you may allow your closure to receive a second argument which will be the current individual item in the array being validated:
$input = [
'channels' => [
[
'type' => 'email',
'address' => 'abigail@example.com',
],
[
'type' => 'url',
'address' => 'https://example.com',
],
],
];
$validator->sometimes('channels.*.address', 'email', function (Fluent $input, Fluent $item) {
return $item->type === 'email';
});
$validator->sometimes('channels.*.address', 'url', function (Fluent $input, Fluent $item) {
return $item->type !== 'email';
});
Like the $input parameter passed to the closure, the $item parameter is an instance of Illuminate\Support\Fluent when the attribute data is an array; otherwise, it is a string.
Validating Arrays
As discussed in the array validation rule documentation, the array rule accepts a list of allowed array keys. If any additional keys are present within the array, validation will fail:
use Illuminate\Support\Facades\Validator;
$input = [
'user' => [
'name' => 'Taylor Otwell',
'username' => 'taylorotwell',
'admin' => true,
],
];
Validator::make($input, [
'user' => ['array:name,username'],
]);
In general, you should always specify the array keys that are allowed to be present within your array. Otherwise, the validator's validate and validated methods will return all of the validated data, including the array and all of its keys, even if those keys were not validated by other nested array validation rules.
Validating Nested Array Input
Validating nested array-based form input fields doesn't have to be a pain. You may use "dot notation" to validate attributes within an array. For example, if the incoming HTTP request contains a photos[profile] field, you may validate it like so:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'photos.profile' => ['required', 'image'],
]);
You may also validate each element of an array. For example, to validate that each email in a given array input field is unique, you may do the following:
$validator = Validator::make($request->all(), [
'users.*.email' => ['email', 'unique:users'],
'users.*.first_name' => ['required_with:users.*.last_name'],
]);
Likewise, you may use the * character when specifying custom validation messages in your language files, making it a breeze to use a single validation message for array-based fields:
'custom' => [
'users.*.email' => [
'unique' => 'Each user must have a unique email address',
]
],
Accessing Nested Array Data
Sometimes you may need to access the value for a given nested array element when assigning validation rules to the attribute. You may accomplish this using the Rule::forEach method. The forEach method accepts a closure that will be invoked for each iteration of the array attribute under validation and will receive the attribute's value and explicit, fully-expanded attribute name. The closure should return an array of rules to assign to the array element:
use App\Rules\HasPermission;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
$validator = Validator::make($request->all(), [
'companies.*.id' => Rule::forEach(function (string|null $value, string $attribute) {
return [
Rule::exists(Company::class, 'id'),
new HasPermission('manage-company', $value),
];
}),
]);
Error Message Indexes and Positions
When validating arrays, you may want to reference the index or position of a particular item that failed validation within the error message displayed by your application. To accomplish this, you may include the :index (starts from 0), :position (starts from 1), or :ordinal-position (starts from 1st) placeholders within your custom validation message:
use Illuminate\Support\Facades\Validator;
$input = [
'photos' => [
[
'name' => 'BeachVacation.jpg',
'description' => 'A photo of my beach vacation!',
],
[
'name' => 'GrandCanyon.jpg',
'description' => '',
],
],
];
Validator::validate($input, [
'photos.*.description' => ['required'],
], [
'photos.*.description.required' => 'Please describe photo #:position.',
]);
Given the example above, validation will fail and the user will be presented with the following error of "Please describe photo #2."
If necessary, you may reference more deeply nested indexes and positions via second-index, second-position, third-index, third-position, etc.
'photos.*.attributes.*.string' => 'Invalid attribute for photo #:second-position.',
Validating Files
Laravel provides a variety of validation rules that may be used to validate uploaded files, such as mimes, image, min, and max. While you are free to specify these rules individually when validating files, Laravel also offers a fluent file validation rule builder that you may find convenient:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\File;
Validator::validate($input, [
'attachment' => [
'required',
File::types(['mp3', 'wav'])
->min(1024)
->max(12 * 1024),
],
]);
Validating File Types
Even though you only need to specify the extensions when invoking the types method, this method actually validates the MIME type of the file by reading the file's contents and guessing its MIME type. A full listing of MIME types and their corresponding extensions may be found at the following location:
svn.apache.org/repos/asf/httpd/htt...
Validating File Sizes
For convenience, minimum and maximum file sizes may be specified as a string with a suffix indicating the file size units. The kb, mb, gb, and tb suffixes are supported:
File::types(['mp3', 'wav'])
->min('1kb')
->max('10mb');
Validating Image Files
If your application accepts images uploaded by your users, you may use the File rule's image constructor method to ensure that the file under validation is an image (jpg, jpeg, png, bmp, gif, or webp).
In addition, the dimensions rule may be used to limit the dimensions of the image:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;
Validator::validate($input, [
'photo' => [
'required',
File::image()
->min(1024)
->max(12 * 1024)
->dimensions(Rule::dimensions()->maxWidth(1000)->maxHeight(500)),
],
]);
[!NOTE]
More information regarding validating image dimensions may be found in the dimension rule documentation.[!WARNING]
By default, theimagerule does not allow SVG files due to the possibility of XSS vulnerabilities. If you need to allow SVG files, you may passallowSvg: trueto theimagerule:File::image(allowSvg: true).
Validating Image Dimensions
You may also validate the dimensions of an image. For example, to validate that an uploaded image is at least 1000 pixels wide and 500 pixels tall, you may use the dimensions rule:
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;
File::image()->dimensions(
Rule::dimensions()
->maxWidth(1000)
->maxHeight(500)
)
[!NOTE]
More information regarding validating image dimensions may be found in the dimension rule documentation.
Validating Passwords
To ensure that passwords have an adequate level of complexity, you may use Laravel's Password rule object:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;
$validator = Validator::make($request->all(), [
'password' => ['required', 'confirmed', Password::min(8)],
]);
The Password rule object allows you to easily customize the password complexity requirements for your application, such as specifying that passwords require at least one letter, number, symbol, or characters with mixed casing:
// Require at least 8 characters...
Password::min(8)
// Require at least one letter...
Password::min(8)->letters()
// Require at least one uppercase and one lowercase letter...
Password::min(8)->mixedCase()
// Require at least one number...
Password::min(8)->numbers()
// Require at least one symbol...
Password::min(8)->symbols()
In addition, you may ensure that a password has not been compromised in a public password data breach leak using the uncompromised method:
Password::min(8)->uncompromised()
Internally, the Password rule object uses the k-Anonymity model to determine if a password has been leaked via the haveibeenpwned.com service without sacrificing the user's privacy or security.
By default, if a password appears at least once in a data leak, it will be considered compromised. You can customize this threshold using the first argument of the uncompromised method:
// Ensure the password appears less than 3 times in the same data leak...
Password::min(8)->uncompromised(3);
Of course, you may chain all the methods in the examples above:
Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols()
->uncompromised()
You may convert a Password rule object to a string suitable for the HTML passwordrules attribute using the toPasswordRulesString method:
<input
type="password"
name="password"
autocomplete="new-password"
passwordrules="{{ Password::defaults()->toPasswordRulesString() }}"
/>
Defining Default Password Rules
You may find it convenient to specify the default validation rules for passwords in a single location of your application. You can easily accomplish this using the Password::defaults method, which accepts a closure. The closure given to the defaults method should return the default configuration of the Password rule. Typically, the defaults rule should be called within the boot method of one of your application's service providers:
use Illuminate\Validation\Rules\Password;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Password::defaults(function () {
$rule = Password::min(8);
return $this->app->isProduction()
? $rule->mixedCase()->uncompromised()
: $rule;
});
}
Then, when you would like to apply the default rules to a particular password undergoing validation, you may invoke the defaults method with no arguments:
'password' => ['required', Password::defaults()],
Occasionally, you may want to attach additional validation rules to your default password validation rules. You may use the rules method to accomplish this:
use App\Rules\ZxcvbnRule;
Password::defaults(function () {
$rule = Password::min(8)->rules([new ZxcvbnRule]);
// ...
});
Custom Validation Rules
Using Rule Objects
Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using rule objects. To generate a new rule object, you may use the make:rule Artisan command. Let's use this command to generate a rule that verifies a string is uppercase. Laravel will place the new rule in the app/Rules directory. If this directory does not exist, Laravel will create it when you execute the Artisan command to create your rule:
php artisan make:rule Uppercase
Once the rule has been created, we are ready to define its behavior. A rule object contains a single method: validate. This method receives the attribute name, its value, and a callback that should be invoked on failure with the validation error message:
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class Uppercase implements ValidationRule
{
/**
* Run the validation rule.
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (strtoupper($value) !== $value) {
$fail('The :attribute must be uppercase.');
}
}
}
Once the rule has been defined, you may attach it to a validator by passing an instance of the rule object with your other validation rules:
use App\Rules\Uppercase;
$request->validate([
'name' => ['required', 'string', new Uppercase],
]);
Translating Validation Messages
Instead of providing a literal error message to the $fail closure, you may also provide a translation string key and instruct Laravel to translate the error message:
if (strtoupper($value) !== $value) {
$fail('validation.uppercase')->translate();
}
If necessary, you may provide placeholder replacements and the preferred language as the first and second arguments to the translate method:
$fail('validation.location')->translate([
'value' => $this->value,
], 'fr');
Accessing Additional Data
If your custom validation rule class needs to access all of the other data undergoing validation, your rule class may implement the Illuminate\Contracts\Validation\DataAwareRule interface. This interface requires your class to define a setData method. This method will automatically be invoked by Laravel (before validation proceeds) with all of the data under validation:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
class Uppercase implements DataAwareRule, ValidationRule
{
/**
* All of the data under validation.
*
* @var array<string, mixed>
*/
protected $data = [];
// ...
/**
* Set the data under validation.
*
* @param array<string, mixed> $data
*/
public function setData(array $data): static
{
$this->data = $data;
return $this;
}
}
Or, if your validation rule requires access to the validator instance performing the validation, you may implement the ValidatorAwareRule interface:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Validation\Validator;
class Uppercase implements ValidationRule, ValidatorAwareRule
{
/**
* The validator instance.
*
* @var \Illuminate\Validation\Validator
*/
protected $validator;
// ...
/**
* Set the current validator.
*/
public function setValidator(Validator $validator): static
{
$this->validator = $validator;
return $this;
}
}
Using Closures
If you only need the functionality of a custom rule once throughout your application, you may use a closure instead of a rule object. The closure receives the attribute's name, the attribute's value, and a $fail callback that should be called if validation fails:
use Illuminate\Support\Facades\Validator;
use Closure;
$validator = Validator::make($request->all(), [
'title' => [
'required',
'max:255',
function (string $attribute, mixed $value, Closure $fail) {
if ($value === 'foo') {
$fail("The {$attribute} is invalid.");
}
},
],
]);
Implicit Rules
By default, when an attribute being validated is not present or contains an empty string, normal validation rules, including custom rules, are not run. For example, the unique rule will not be run against an empty string:
use Illuminate\Support\Facades\Validator;
$rules = ['name' => ['unique:users,name']];
$input = ['name' => ''];
Validator::make($input, $rules)->passes(); // true
For a custom rule to run even when an attribute is empty, the rule must imply that the attribute is required. To quickly generate a new implicit rule object, you may use the make:rule Artisan command with the --implicit option:
php artisan make:rule Uppercase --implicit
[!WARNING]
An "implicit" rule only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
Laravel 13 中文文档
关于 LearnKu
推荐文章: