Tech Verse Logo
Enable dark mode
Form Validation with Livewire's #[Validate] Attribute

Form Validation with Livewire's #[Validate] Attribute

•Updated •10 min read

Put #[Validate('rule')] on a public property and Livewire checks it whenever that property updates through wire:model.live, then call $this->validate() before saving. Stack one attribute per rule for custom messages, and use a rules() method for runtime rules such as Rule::unique()->ignore() on a profile form.

Livewire's #[Validate] attribute puts a property's validation rules on the property itself. Livewire then checks that property every time it changes, and $this->validate() checks all of them before you save. That covers most forms. The parts that trip people up are custom messages on piped rules, nested array rules, and anything that needs a runtime value, such as a unique check that has to ignore the current user.

Every example below was run in a fresh Laravel app with the current Livewire release, and each behaviour described was confirmed with Livewire::test(). The tests are at the end.

How does the #[Validate] attribute work?

You import Livewire\Attributes\Validate, attach it to a public property, and pass a rule string or array, exactly as you would to Laravel's validator. Here's a post scheduling form with three fields that each use the attribute a little differently.

<?php

namespace App\Livewire;

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

class CreatePost extends Component
{
    #[Validate('required', message: 'Give the post a title.')]
    #[Validate('min:5', message: 'That title is too short.')]
    public string $title = '';

    #[Validate('required|min:20', as: 'post body')]
    public string $body = '';

    #[Validate('required|date|after:today', onUpdate: false)]
    public string $publishAt = '';

    public function save(): void
    {
        $validated = $this->validate();

        session()->flash('status', "Scheduled: {$validated['title']}");

        $this->reset();
    }

    public function render()
    {
        return view('livewire.create-post');
    }
}

The attribute's constructor takes six arguments, and these are all of them: rule, attribute, as, message, onUpdate and translate. You can check the list in the BaseValidate source on GitHub. There's no rules: parameter, so #[Validate(rules: [...])] fails with Error: Unknown named parameter $rules as soon as Livewire reads the attribute. Pass the array as the first argument instead, either positionally or as rule:.

Calling $this->validate() in save() still matters. Real-time validation only checks fields the user has touched, so if someone submits an empty form, the attribute rules never ran. validate() runs every rule, throws a ValidationException if anything fails (Livewire turns that into the $errors bag for the view), and returns only the validated data.

Real-time validation and onUpdate

By default, a property with #[Validate] is validated whenever Livewire receives an update for it. Under the hood the attribute's update hook calls validateOnly() for that one property, so an error on the title doesn't light up every other field. The catch is that "receives an update" means a network request, and plain wire:model doesn't send one when the user types. It only syncs with the next action, such as the form submit. To see errors while the user fills the form in, use wire:model.live (request on every keystroke, debounced) or wire:model.live.blur (request when the field loses focus).

<form wire:submit="save">
    <input type="text" wire:model.live.blur="title">
    @error('title') <p>{{ $message }}</p> @enderror

    <textarea wire:model.live.blur="body"></textarea>
    @error('body') <p>{{ $message }}</p> @enderror

    <input type="date" wire:model="publishAt">
    @error('publishAt') <p>{{ $message }}</p> @enderror

    <button type="submit">Schedule</button>
</form>

I'd use .live.blur for most text inputs. Validating on every keystroke tells the user their email address is invalid while they're still typing it, which is irritating and costs a request per pause. Note that .blur without .live only delays the client-side sync. It doesn't send a request, so nothing gets validated until submit.

onUpdate: false switches real-time validation off for one property while keeping its rules for validate(). The publish date above uses it. The tests confirm that setting publishAt to a past date produces no error at all, and calling save() then fails with the after rule. That's useful for fields whose rules depend on other fields, or for anything expensive, like a rule that hits an external API.

Custom messages and attribute names

The message argument replaces Laravel's default message, but a single message string only works when the attribute has a single rule. Livewire builds the message key from the first rule's name, taking everything before the colon. For #[Validate('required|min:2', message: 'Name must be at least 2 characters')] that key is name.required|min, which matches no rule. You get no error and no warning, just Laravel's default text ("The name field must be at least 2 characters."). I confirmed this in a test, and it's an easy one to miss because the form still validates.

There are two ways to do it properly. Stack one attribute per rule, as the title does in CreatePost: two #[Validate] lines, each with its own rule and message. The attribute is repeatable, and the rules merge. Or pass message as an array keyed by field.rule, which is what you'll want for array fields (see the next section).

For the field name inside Laravel's default messages, use as. The body in CreatePost has as: 'post body', so a short body produces "The post body field must be at least 20 characters." instead of "The body field...". Without it you'd get the property name, which for camelCase properties reads like "The publish at field". The attribute argument does the same job, and it also accepts an array keyed by field, which is handy for tags.*.

Both message and as go through Laravel's trans() helper by default, so you can pass a translation key such as 'validation.custom.title'. If a literal message happens to collide with a key in your language files, add translate: false.

Validating arrays and nested data

For an array property, pass the rule as an array keyed by field name, so you can cover both the array and its items. Livewire recognises the keyed form when the first key isn't numeric, and it registers every key as a rule.

<?php

namespace App\Livewire;

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

class TagEditor extends Component
{
    #[Validate([
        'tags' => 'required|array|min:1|max:5',
        'tags.*' => 'required|string|distinct|max:30',
    ], message: [
        'tags.required' => 'Add at least one tag.',
        'tags.max' => 'Five tags is the limit.',
        'tags.*.max' => 'Each tag must be 30 characters or fewer.',
        'tags.*.distinct' => 'You have used this tag twice.',
    ], attribute: [
        'tags.*' => 'tag',
    ])]
    public array $tags = [];

    public function addTag(): void
    {
        $this->tags[] = '';
    }

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

    public function render()
    {
        return view('livewire.tag-editor');
    }
}
<form wire:submit="save">
    @foreach ($tags as $index => $tag)
        <input type="text" wire:model.live.blur="tags.{{ $index }}">
        @error("tags.{$index}") <p>{{ $message }}</p> @enderror
    @endforeach

    @error('tags') <p>{{ $message }}</p> @enderror

    <button type="button" wire:click="addTag">Add tag</button>
    <button type="submit">Save</button>
</form>

The attribute array turns the default message for an empty item into "The tag field is required." instead of "The tags.2 field is required.", and the message array keys work exactly like Laravel's custom messages, wildcards included. With distinct, Laravel flags both duplicates, so tags.0 and tags.1 each get "You have used this tag twice."

One behaviour is worth knowing before you write tests. Real-time validation runs against the path that changed. When the input bound to tags.1 changes, Livewire validates tags.1, so the tags.* rules apply. If you replace the whole array in one go (in a test, ->set('tags', [...])), only the top-level tags rule runs, and a 31-character item slips through until save() calls validate(). In the browser each input updates its own index, so this mostly shows up as a test that passes when you expected it to fail.

When should you use the rules() method instead?

Use a rules() method whenever a rule needs a value that only exists at runtime. PHP attribute arguments must be constant expressions, so you can't call Auth::id() or build Rule::unique(...)->ignore(...) inside #[Validate]. The classic case is a profile form. A plain unique:users,email rule rejects the user's own address the moment they save without changing it, because their row already holds that email.

This profile component mixes both styles. Name and avatar use the attribute, and email comes from rules(), with an empty #[Validate] on the property. That empty attribute matters. Livewire only applies rules() when you call validate(), and the bare attribute brings back real-time validation for that property using the rules from the method.

<?php

namespace App\Livewire;

use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Validate;
use Livewire\Component;
use Livewire\WithFileUploads;

class EditProfile extends Component
{
    use WithFileUploads;

    #[Validate('required|string|min:3|max:255')]
    public string $name = '';

    #[Validate]
    public string $email = '';

    #[Validate('nullable|image|max:2048')]
    public $avatar;

    public function mount(): void
    {
        $this->name = Auth::user()->name;
        $this->email = Auth::user()->email;
    }

    protected function rules(): array
    {
        return [
            'email' => [
                'required',
                'email',
                Rule::unique('users', 'email')->ignore(Auth::id()),
            ],
        ];
    }

    public function save(): void
    {
        $validated = $this->validate();

        $user = Auth::user();
        $user->name = $validated['name'];
        $user->email = $validated['email'];

        if ($this->avatar) {
            $user->avatar_path = $this->avatar->store('avatars', 'public');
        }

        $user->save();

        $this->reset('avatar');

        session()->flash('status', 'Profile updated.');
    }

    public function render()
    {
        return view('livewire.edit-profile');
    }
}

The component assumes a nullable avatar_path string column on users and a route behind the auth middleware. In the tests, saving the profile with an unchanged email passes, and switching to another user's address fails on unique. Also keep rules() as a method. Don't name a property rules, messages or validationAttributes, because Livewire reserves those names.

File uploads, done correctly

A file input only works if the component uses the WithFileUploads trait. The trait provides the server-side methods (_startUpload, _finishUpload) that Livewire's JavaScript calls while it uploads, so without it the upload fails and $avatar never holds a file. With the trait, the file goes to a temporary location as soon as it's picked, and the property holds a TemporaryUploadedFile. Because the avatar has #[Validate], the image and max:2048 rules (kilobytes) run on that temporary upload straight away. In the tests a PDF fails on image and a 3 MB JPEG fails on max, before the user clicks save.

The other mistake is passing $validated straight to $user->update(). The validated array holds the temporary upload object, not a path, and it has to be moved somewhere permanent. store('avatars', 'public') does that and returns the path, which is what goes in the database. Resetting avatar afterwards clears the input so a second save doesn't upload the same file again. The Livewire file uploads documentation covers previews, multiple files and S3 temporary storage.

Form objects

Once a component has more than a handful of fields, move them into a form object. A class extending Livewire\Form holds the properties, and #[Validate] works on them the same way, real-time validation included.

<?php

namespace App\Livewire\Forms;

use Livewire\Attributes\Validate;
use Livewire\Form;

class ContactForm extends Form
{
    #[Validate('required|min:2')]
    public string $name = '';

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

    #[Validate('required|min:10', as: 'message')]
    public string $body = '';
}
<?php

namespace App\Livewire;

use App\Livewire\Forms\ContactForm;
use App\Models\ContactMessage;
use Livewire\Component;

class ContactPage extends Component
{
    public ContactForm $form;

    public function send(): void
    {
        $this->form->validate();

        ContactMessage::create($this->form->all());

        $this->form->reset();

        session()->flash('status', 'Thanks, we will be in touch.');
    }

    public function render()
    {
        return view('livewire.contact-page');
    }
}
<form wire:submit="send">
    <input type="text" wire:model.live.blur="form.name">
    @error('form.name') <p>{{ $message }}</p> @enderror

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

    <textarea wire:model="form.body"></textarea>
    @error('form.body') <p>{{ $message }}</p> @enderror

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

Two details are different from a plain component. Bindings and error keys are prefixed with the property name, so it's wire:model="form.email" and @error('form.email'). And you validate through the form, with $this->form->validate(), then read the data with $this->form->all(). ContactMessage here is an ordinary Eloquent model with name, email and body fillable. The as: 'message' on body means the error reads "The message field is required." rather than naming the property.

A form object can also have its own rules() method, so the unique-ignoring-self trick from the profile works there too. See the Livewire forms documentation for resetting, pulling values and form-level rules().

Testing validation with Livewire::test

Livewire's test helper calls the same update hooks the browser does, so ->set() on a property with #[Validate] runs real-time validation, and you can assert on it immediately. assertHasErrors takes a field name, a list of fields, or a field paired with the rule name that should fail. That last form is the one to use, because it proves the right rule fired.

<?php

namespace Tests\Feature;

use App\Livewire\ContactPage;
use App\Livewire\CreatePost;
use App\Livewire\EditProfile;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
use Tests\TestCase;

class PostFormValidationTest extends TestCase
{
    use RefreshDatabase;

    public function test_title_is_checked_as_soon_as_it_changes(): void
    {
        Livewire::test(CreatePost::class)
            ->set('title', 'Hi')
            ->assertHasErrors(['title' => 'min'])
            ->assertSee('That title is too short.')
            ->set('title', 'A proper title')
            ->assertHasNoErrors('title');
    }

    public function test_publish_date_waits_for_save(): void
    {
        Livewire::test(CreatePost::class)
            ->set('publishAt', '2001-01-01')
            ->assertHasNoErrors('publishAt')
            ->call('save')
            ->assertHasErrors(['publishAt' => 'after']);
    }

    public function test_user_can_keep_their_own_email(): void
    {
        $user = User::factory()->create(['email' => 'me@example.com']);
        User::factory()->create(['email' => 'taken@example.com']);

        $this->actingAs($user);

        Livewire::test(EditProfile::class)
            ->call('save')
            ->assertHasNoErrors();

        Livewire::test(EditProfile::class)
            ->set('email', 'taken@example.com')
            ->assertHasErrors(['email' => 'unique']);
    }

    public function test_avatar_is_stored_on_the_public_disk(): void
    {
        Storage::fake('public');
        $user = User::factory()->create();

        $this->actingAs($user);

        Livewire::test(EditProfile::class)
            ->set('avatar', UploadedFile::fake()->image('me.jpg'))
            ->call('save')
            ->assertHasNoErrors();

        Storage::disk('public')->assertExists($user->fresh()->avatar_path);
    }

    public function test_form_object_errors_are_prefixed(): void
    {
        Livewire::test(ContactPage::class)
            ->set('form.email', 'not-an-email')
            ->assertHasErrors(['form.email' => 'email']);
    }
}

All five tests pass against the components above. assertSee checks that the stacked custom message actually reaches the rendered view, which is how you'd catch the single-message problem from earlier. For the full list of validation assertions, see Livewire's validation documentation.

WRITTEN BY

Full Stack Software Engineer | Laravel · Next.js · AWS

Full Stack Software Engineer with 7+ years of experience building scalable, secure web applications with Laravel, PHP, React, Next.js, and AWS for SaaS, CRM, telecom, and e-commerce companies. Specialized in cloud telephony (FreeSWITCH, SMPP, WebRTC): increased concurrent call capacity by 40% and cut report queries to under 500 ms. Author of open-source Laravel packages with 10K+ downloads on Packagist. Led a team of 4 engineers and shipped production systems for clients in the UAE, USA, India, Saudi Arabia, and Bangladesh.

How we research, write and check articles

    Latest Posts

    View All

    Next.js Middleware Authentication and Token Refresh Flows

    Next.js Middleware Authentication and Token Refresh Flows

    Livewire Performance Optimization Under High Load

    Livewire Performance Optimization Under High Load

    Configuring Nginx Upstream Keepalive for Node Backends

    Configuring Nginx Upstream Keepalive for Node Backends

    Enforcing Immutable State Patterns in React

    Enforcing Immutable State Patterns in React

    FastAPI Dependency Overrides for Integration Testing

    FastAPI Dependency Overrides for Integration Testing

    Stopping Layout Shifts in Next.js Dynamic Imports

    Stopping Layout Shifts in Next.js Dynamic Imports

    Optimizing Agentic Tool Calling Latency

    Optimizing Agentic Tool Calling Latency

    Fixing React Server Component Serialization Errors

    Fixing React Server Component Serialization Errors

    Next.js Route Handler Streaming with ReadableStream

    Next.js Route Handler Streaming with ReadableStream

    React Form Performance: Uncontrolled Inputs and FormData

    React Form Performance: Uncontrolled Inputs and FormData