Skip to content
全部文档

Validate

#[Validate] 属性将验证规则与组件属性关联,支持自动实时验证和简洁的规则声明。

基本用法

#[Validate] 属性应用到需要验证的属性上:

php
<?php // resources/views/components/post/⚡create.blade.php

use Livewire\Attributes\Validate;
use Livewire\Component;
use App\Models\Post;

new class extends Component {
    #[Validate('required|min:3')] // [tl! highlight]
    public $title = '';

    #[Validate('required|min:3')] // [tl! highlight]
    public $content = '';

    public function save()
    {
        $this->validate();

        Post::create([
            'title' => $this->title,
            'content' => $this->content,
        ]);

        return redirect('/posts');
    }
};
?>

<div>
    <input type="text" wire:model="title">
    @error('title') <span class="error">{{ $message }}</span> @enderror

    <textarea wire:model="content"></textarea>
    @error('content') <span class="error">{{ $message }}</span> @enderror

    <button wire:click="save">Save Post</button>
</div>

使用 #[Validate] 后,Livewire 会在每次更新时自动验证属性,为用户提供即时反馈。

工作原理

当你给属性添加 #[Validate] 时:

  1. 自动验证 - 属性每次更新时都会被验证
  2. 实时反馈 - 用户立即看到验证错误
  3. 手动验证 - 保存前仍需调用 $this->validate(),以确保所有属性都已验证

实时验证

默认情况下,#[Validate] 会在属性更新时进行验证:

php
<?php // resources/views/components/⚡registration.blade.php

use Livewire\Attributes\Validate;
use Livewire\Component;

new class extends Component {
    #[Validate('required|email|unique:users,email')]
    public $email = '';

    #[Validate('required|min:8')]
    public $password = '';
};
?>

<div>
    <input type="email" wire:model.live.blur="email">
    @error('email') <span>{{ $message }}</span> @enderror

    <input type="password" wire:model.live.blur="password">
    @error('password') <span>{{ $message }}</span> @enderror
</div>

用户填写表单时,会立即收到验证反馈。

禁用自动验证

若仅在显式调用 $this->validate() 时验证,请使用 onUpdate: false

php
<?php // resources/views/components/post/⚡create.blade.php

use Livewire\Attributes\Validate;
use Livewire\Component;
use App\Models\Post;

new class extends Component {
    #[Validate('required|min:3', onUpdate: false)] // [tl! highlight]
    public $title = '';

    #[Validate('required|min:3', onUpdate: false)] // [tl! highlight]
    public $content = '';

    public function save()
    {
        $validated = $this->validate();
        Post::create($validated);
        return redirect('/posts');
    }
};

现在验证仅在调用 save() 时运行,而不是在每次属性更新时。

自定义属性名称

自定义验证消息中的字段名称:

php
#[Validate('required', as: 'date of birth')] // [tl! highlight]
public $dob;

错误消息将是「The date of birth field is required」,而不是「The dob field is required」。

自定义验证消息

覆盖默认验证消息:

php
#[Validate('required', message: 'Please provide a post title')] // [tl! highlight]
public $title;

对于多条规则,使用多个属性:

php
#[Validate('required', message: 'Please provide a post title')]
#[Validate('min:3', message: 'This title is too short')]
public $title;

数组验证

验证数组属性及其子项:

php
<?php // resources/views/components/⚡task-list.blade.php

use Livewire\Attributes\Validate;
use Livewire\Component;

new class extends Component {
    #[Validate([
        'tasks' => 'required|array|min:1',
        'tasks.*' => 'required|string|min:3',
    ])]
    public $tasks = [];

    public function addTask()
    {
        $this->tasks[] = '';
    }
};

这会同时验证数组本身和每个单独的任务。

限制

WARNING

不支持 Rule 对象

PHP 属性无法直接使用 Laravel 的 Rule 对象。对于 Rule::exists() 等复杂规则,请改用 rules() 方法:

php
protected function rules()
{
    return [
        'email' => ['required', 'email', Rule::unique('users')->ignore($this->userId)],
    ];
}

何时使用

在以下情况使用 #[Validate]

  • 构建带有实时验证反馈的表单
  • 将验证规则与属性定义放在一起
  • 创建简单、可读的验证逻辑
  • 实现内联验证以改善 UX

在以下情况使用 rules() 方法:

  • 需要 Laravel 的 Rule 对象
  • 规则依赖于动态值
  • 处理复杂的条件验证
  • 更倾向于集中定义规则

示例:联系表单

下面是一个带验证的完整联系表单:

php
<?php // resources/views/pages/⚡contact.blade.php

use Livewire\Attributes\Validate;
use Livewire\Component;
use App\Mail\ContactMessage;
use Illuminate\Support\Facades\Mail;

new class extends Component {
    #[Validate('required|min:2', as: 'name')]
    public $name = '';

    #[Validate('required|email')]
    public $email = '';

    #[Validate('required')]
    public $subject = '';

    #[Validate('required|min:10', as: 'message')]
    public $message = '';

    public function submit()
    {
        $validated = $this->validate();

        Mail::to('support@example.com')->send(new ContactMessage($validated));

        session()->flash('success', 'Message sent successfully!');

        $this->reset();
    }
};
?>

<div>
    @if (session('success'))
        <div class="alert">{{ session('success') }}</div>
    @endif

    <form wire:submit="submit">
        <div>
            <input type="text" wire:model.live.blur="name" placeholder="Your name">
            @error('name') <span class="error">{{ $message }}</span> @enderror
        </div>

        <div>
            <input type="email" wire:model.live.blur="email" placeholder="Your email">
            @error('email') <span class="error">{{ $message }}</span> @enderror
        </div>

        <div>
            <input type="text" wire:model.live.blur="subject" placeholder="Subject">
            @error('subject') <span class="error">{{ $message }}</span> @enderror
        </div>

        <div>
            <textarea wire:model.live.blur="message" placeholder="Your message"></textarea>
            @error('message') <span class="error">{{ $message }}</span> @enderror
        </div>

        <button type="submit">Send Message</button>
    </form>
</div>

用户填写表单时会立即获得反馈,并带有友好的字段名和有用的错误消息。

了解更多

有关验证的完整文档,包括表单对象、自定义规则和测试,请参阅 验证文档

参考

php
#[Validate(
    mixed $rule = null,
    ?string $attribute = null,
    ?string $as = null,
    mixed $message = null,
    bool $onUpdate = true,
    bool $translate = true,
)]
参数类型默认值说明
$rulemixednull要应用的验证规则
$attribute?stringnull验证错误消息的自定义属性名
$as?stringnull显示在验证错误消息中的友好名称
$messagemixednull验证失败时的自定义错误消息
$onUpdatebooltrue属性更新时是否运行验证
$translatebooltrue是否翻译验证消息