You're browsing the documentation for an old version of Livewire. Consider upgrading your project to Livewire 3.x.

Validation

Be amazing at Livewire
with our in-depth screencasts.
Watch Now

Introduction

Validation in Livewire should feel similar to standard form validation in Laravel. In short, Livewire provides a $rules property for setting validation rules on a per-component basis, and a $this->validate() method for validating a component's properties using those rules.

Here's a simple example of a form in Livewire being validated.

            
1class ContactForm extends Component
2{
3 public $name;
4 public $email;
5 
6 protected $rules = [
7 'name' => 'required|min:6',
8 'email' => 'required|email',
9 ];
10 
11 public function submit()
12 {
13 $this->validate();
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}
            
1<form wire:submit.prevent="submit">
2 <input type="text" wire:model="name">
3 @error('name') <span class="error">{{ $message }}</span> @enderror
4 
5 <input type="text" wire:model="email">
6 @error('email') <span class="error">{{ $message }}</span> @enderror
7 
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')

If you need to define rules dynamically, you can substitute the $rules property for the rules() method on the component:

        
1class ContactForm extends Component
2{
3 public $name;
4 public $email;
5 
6 protected function rules()
7 {
8 return [
9 'name' => 'required|min:6',
10 'email' => ['required', 'email', 'not_in:' . auth()->user()->email],
11 ];
12 }
13}

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:

            
1class ContactForm extends Component
2{
3 public $name;
4 public $email;
5 
6 protected $rules = [
7 'name' => 'required|min:6',
8 'email' => 'required|email',
9 ];
10 
11 public function updated($propertyName)
12 {
13 $this->validateOnly($propertyName);
14 }
15 
16 public function saveContact()
17 {
18 $validatedData = $this->validate();
19 
20 Contact::create($validatedData);
21 }
22}
            
1<form wire:submit.prevent="saveContact">
2 <input type="text" wire:model="name">
3 @error('name') <span class="error">{{ $message }}</span> @enderror
4 
5 <input type="text" wire:model="email">
6 @error('email') <span class="error">{{ $message }}</span> @enderror
7 
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.

Validating with rules outside of the $rules property

If for whatever reason you want to validate using rules other than the ones defined in the $rules property, you can always do this by passing the rules directly into the validate() and validateOnly() methods.

            
1class ContactForm extends Component
2{
3 public $name;
4 public $email;
5 
6 public function updated($propertyName)
7 {
8 $this->validateOnly($propertyName, [
9 'name' => 'min:6',
10 'email' => 'email',
11 ]);
12 }
13 
14 public function saveContact()
15 {
16 $validatedData = $this->validate([
17 'name' => 'required|min:6',
18 'email' => 'required|email',
19 ]);
20 
21 Contact::create($validatedData);
22 }
23}

Customize Error Message & Attributes

If you wish to customize the validation messages used by a Livewire component, you can do so with the $messages property.

If you want to keep the default Laravel validation messages, but just customize the :attribute portion of the message, you can specify custom attribute names using the $validationAttributes property.

            
1class ContactForm extends Component
2{
3 public $email;
4 
5 protected $rules = [
6 'email' => 'required|email',
7 ];
8 
9 protected $messages = [
10 'email.required' => 'The Email Address cannot be empty.',
11 'email.email' => 'The Email Address format is not valid.',
12 ];
13 
14 protected $validationAttributes = [
15 'email' => 'email address'
16 ];
17 
18 public function updated($propertyName)
19 {
20 $this->validateOnly($propertyName);
21 }
22 
23 public function saveContact()
24 {
25 $validatedData = $this->validate();
26 
27 Contact::create($validatedData);
28 }
29}

You can substitute the $messages property for the messages() method on the component.

If you are not using the global $rules validation property, then you can pass custom messages and attributes directly into validate().

            
1class ContactForm extends Component
2{
3 public $email;
4 
5 public function saveContact()
6 {
7 $validatedData = $this->validate(
8 ['email' => 'required|email'],
9 [
10 'email.required' => 'The :attribute cannot be empty.',
11 'email.email' => 'The :attribute format is not valid.',
12 ],
13 ['email' => 'Email Address']
14 );
15 
16 Contact::create($validatedData);
17 }
18}

Direct Error Message Manipulation

The validate() and validateOnly() methods 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// Quickly add a validation message to the error bag.
2$this->addError('email', 'The email field is invalid.');
3 
4// These two methods do the same thing, they clear the error bag.
5$this->resetErrorBag();
6$this->resetValidation();
7 
8// If you only want to clear errors for one key, you can use:
9$this->resetValidation('email');
10$this->resetErrorBag('email');
11 
12// This will give you full access to the error bag.
13$errors = $this->getErrorBag();
14// With this error bag instance, you can do things like this:
15$errors->add('some-key', 'Some message');

Access Validator instance

Sometimes you may want to access the Validator instance that Livewire uses in the validate() and validateOnly() methods. This is possible using the withValidator method. The closure you provide receives the fully constructed validator as an argument, allowing you to call any of its methods before the validation rules are actually evaluated.

            
1use Illuminate\Validation\Validator;
2 
3class ContactForm extends Component
4{
5 public function save()
6 {
7 $this->withValidator(function (Validator $validator) {
8 $validator->after(function ($validator) {
9 if ($this->somethingElseIsInvalid()) {
10 $validator->errors()->add('field', 'Something is wrong with this field!');
11 }
12 });
13 })->validate();
14 }
15}

Testing Validation

Livewire provides useful testing utilities for validation scenarios. Let's 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 Illuminate\Support\Facades\Validator;
2 
3class ContactForm extends Component
4{
5 public $email;
6 
7 public function saveContact()
8 {
9 $validatedData = Validator::make(
10 ['email' => $this->email],
11 ['email' => 'required|email'],
12 ['required' => 'The :attribute field is required'],
13 )->validate();
14 
15 Contact::create($validatedData);
16 }
17}
            
1<div>
2 Email: <input wire:model.lazy="email">
3 
4 @if($errors->has('email'))
5 <span>{{ $errors->first('email') }}</span>
6 @endif
7 
8 <button wire:click="saveContact">Save Contact</button>
9</div>
You might be wondering if you can use Laravel's "FormRequest"s. Due to the nature of Livewire, hooking into the http request wouldn't make sense. For now, this functionality is not possible or recommended.
← Previous Topic Nesting Components
Next Topic → File Uploads