Validation
Validation in Livewire should feel similar to standard form validation in Laravel.
Here's a simple example of a form in Livewire being validated.
1use Livewire\Component; 2 3class ContactForm extends Component 4{ 5 public $name; 6 public $email; 7 8 public function submit() 9 {10 $this->validate([11 'name' => 'required|min:6',12 'email' => 'required|email',13 ]);14 15 // Execution doesn't reach here if validation fails.16 17 Contact::create([18 'name' => $this->name,19 'email' => $this->email,20 ]);21 }22 23 public function render()24 {25 return view('livewire.contact-form');26 }27}
1<form wire:submit.prevent="submit">2 <input type="text" wire:model="name">3 @error('name') <span class="error">{{ $message }}</span> @enderror4 5 <input type="text" wire:model="email">6 @error('email') <span class="error">{{ $message }}</span> @enderror7 8 <button type="submit">Save Contact</button>9</form>
If validation fails, a standard ValidationException
is thrown (and caught by Livewire), and the standard $errors
object is available inside the component's view. Because of this, any existing code you have, likely a Blade include, for handling validation in the rest of your application will apply here as well.
You can also add custom key/message pairs to the error bag.
1$this->addError('key', 'message')
Real-time Validation
Sometimes it's useful to validate a form field as a user types into it. Livewire makes "real-time" validation simple with the $this->validateOnly()
method.
To validate an input field after every update, we can use Livewire's updated
hook:
1use Livewire\Component; 2 3class ContactForm extends Component 4{ 5 public $name; 6 public $email; 7 8 public function updated($field) 9 {10 $this->validateOnly($field, [11 'name' => 'min:6',12 'email' => 'email',13 ]);14 }15 16 public function saveContact()17 {18 $validatedData = $this->validate([19 'name' => 'required|min:6',20 'email' => 'required|email',21 ]);22 23 Contact::create($validatedData);24 }25 26 public function render()27 {28 return view('livewire.contact-form');29 }30}
1<form wire:submit.prevent="saveContact">2 <input type="text" wire:model="name">3 @error('name') <span class="error">{{ $message }}</span> @enderror4 5 <input type="text" wire:model="email">6 @error('email') <span class="error">{{ $message }}</span> @enderror7 8 <button type="submit">Save Contact</button>9</form>
Let's break down exactly what is happening in this example:
- The user types into the "name" field
- As the user types in their name, a validation message is shown if it's less than 6 characters
- The user can switch to entering their email, and the validation message for the name still shows
- When the user submits the form, there is a final validation check, and the data is persisted.
If you are wondering, "why do I need validateOnly
? Can't I just use validate
?". The reason is because otherwise, every single update to any field would validate ALL of the fields. This can be a jarring user experience. Imagine if you typed one character into the first field of a form, and all of a sudden every single field had a validation message. validateOnly
prevents that, and only validates the current field being updated.
Direct Error Message Manipulation
The validate()
and validateOnly()
method should handle most cases, but sometimes you may want direct control over Livewire's internal ErrorBag.
Livewire provides a handful of methods for you to directly manipulate the ErrorBag.
From anywhere inside a Livewire component class, you can call the following methods:
1$this->addError('email', 'The email field is invalid.'); 2// Quickly add a validation message to the error bag. 3 4$this->resetErrorBag(); 5$this->resetValidation(); 6// These two methods do the same thing. They clear the error bag. 7// If you only want to clear errors for one key, you can use: 8$this->resetValidation('email'); 9$this->resetErrorBag('email');10 11$errors = $this->getErrorBag();12// This will give you full access to the error bag,13// allowing you to do things like this:14$errors->add('some-key', 'Some message');
Testing Validation
Livewire provides useful testing utilities for validation scenarios. Let's a write a simple test for the original "Contact Form" component.
1/** @test */2public function name_and_email_fields_are_required_for_saving_a_contact()3{4 Livewire::test('contact-form')5 ->set('name', '')6 ->set('email', '')7 ->assertHasErrors(['name', 'email']);8}
This is useful, but we can take it one step further and actually test against specific validation rules:
1/** @test */ 2public function name_and_email_fields_are_required_for_saving_a_contact() 3{ 4 Livewire::test('contact-form') 5 ->set('name', '') 6 ->set('email', '') 7 ->assertHasErrors([ 8 'name' => 'required', 9 'email' => 'required',10 ]);11}
Livewire also offers the inverse of assertHasErrors
-> assertHasNoErrors()
:
1/** @test */2public function name_field_is_required_for_saving_a_contact()3{4 Livewire::test('contact-form')5 ->set('name', '')6 ->set('email', 'foo')7 ->assertHasErrors(['name' => 'required'])8 ->assertHasNoErrors(['email' => 'required']);9}
For more examples of supported syntax for these two methods, take a look at the Testing Docs.
Custom validators
If you wish to use your own validation system in Livewire, that isn't a problem. Livewire will catch ValidationException
and provide the errors to the view just like using $this->validate()
.
For example:
1use Livewire\Component; 2use Illuminate\Support\Facades\Validator; 3 4class ContactForm extends Component 5{ 6 public $email; 7 8 public function saveContact() 9 {10 $validatedData = Validator::make(11 ['email' => $this->email],12 ['email' => 'required|email'],13 ['required' => 'The :attribute field is required'],14 )->validate();15 16 Contact::create($validatedData);17 }18 19 public function render()20 {21 return view('livewire.contact-form');22 }23}
1<div>2 Email: <input wire:model.lazy="email">3 4 @if($errors->has('email'))5 <span>{{ $errors->first('email') }}</span>6 @endif7 8 <button wire:click="saveContact">Save Contact</button>9</div>