Back to Course |
Livewire 3 From Scratch: Practical Course

Live Update with Live Validation

Currently, our form inputs are updated only after the submit is clicked. In this short lesson, let's see two methods to update properties instantly as the user is typing to add a "live" validation.


Update Values Instantly

In Livewire version 3, by default, the wire:model directive updates the values only on the next server request.

We must add .live to the wire:model directive to update instantly.

<form method="POST" wire:submit="save">
<div>
<label for="title" class="block font-medium text-sm text-gray-700">Title</label>
<input id="title" wire:model="form.title" class="block mt-1 w-full border-gray-300 rounded-md shadow-sm" type="text" />
<input id="title" wire:model.live="form.title" class="block mt-1 w-full border-gray-300 rounded-md shadow-sm" type="text" />
@error('form.title')
<span class="mt-2 text-sm text-red-600">{{ $message }}</span>
@enderror
</div>
 
<div class="mt-4">
<label for="body" class="block font-medium text-sm text-gray-700">Body</label>
<textarea id="body" wire:model="form.body" class="block mt-1 w-full border-gray-300 rounded-md shadow-sm"></textarea>
<textarea id="body" wire:model.live="form.body" class="block mt-1 w-full border-gray-300 rounded-md shadow-sm"></textarea>
@error('form.body')
<span class="mt-2 text-sm text-red-600">{{ $message }}</span>
@enderror
</div>
 
<button class="mt-4 px-4 py-2 bg-gray-800 rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700">
Save
</button>
</form>

Now, if you start writing, the validation will show after the first letter. But be aware that this hits the server every time.

wire:model.live server requests

Notice: In version 2, it was the opposite way. The "live" behavior was the default, and we had to use .defer for the wire:model to turn it off. It caused too many server requests. That's why the default was changed in v3.


Update When Focus Removed

Another "middle ground" between the two ways mentioned above is to update when a user removes focus from the input. We need to add .blur to the wire:model directive for this.

<input id="title" wire:model.blur="form.title" ... />
 
<textarea id="body" wire:model.blur="form.body" ...></textarea>

Now, try to write a few letters in the title and remove focus from it. The validation will be shown only then.


So, in this way, you may add a lot of "live" dynamic behavior on your Livewire pages.