How to implement real-time validation in Livewire 2?

In this tutorial, I will give you an example of “implement real-time validation in Livewire 2”, So you can easily apply it to your Laravel 8, and Laravel 9 applications.

First, what we’re doing here, This is the example :

implement real time validation in Livewire 2

 real time validation in Livewire

reset implement real time validation in Livewire 2

Livewire custom validation rule

Livewire provides the best features, and one of them is real-time validation using laravel livewire with livewire lifecycle hooks. Lifecycle hooks allow you to run code at any part of the component’s lifecycle, or before specific properties are updated. It works like a little SPA, that’s why livewire hooks are very useful. For this section, we will use updated hooks for real-time validation.

Let’s implement real-time validation in Livewire 2

Generating Migration with Model :

php artisan make:model RealTimeVal -m

Migration Structure :

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('real_time_vals', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('phone');
            $table->string('address');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('real_time_vals');
    }
};

Run Migration :

php artisan migrate
table migration in livewire

app\Models\RealTimeVal.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RealTimeVal extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'email','phone', 'address'];
}

Create a Livewire Component

php artisan livewire:make real time validation

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Livewire\RealTimeValidationExample;


#Test Real-Time Validation
Route::get('create/user', RealTimeValidationExample::class);


resources\views\livewire\real-time-validation-example.blade.php

<div>
   <div class="content-header">
      <div class="container-fluid">
         <div class="row mb-2">
            <div class="col-sm-6">
               <h1 class="m-0">Create User</h1>
            </div>
            <div class="col-sm-6">
               <ol class="breadcrumb float-sm-right">
                  <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}">Dashboard</a></li>
                  <li class="breadcrumb-item active">User</li>
               </ol>
            </div>
         </div>
      </div>
   </div>
   <!-- Main content -->
   <section class="content">
      <div class="container-fluid">
         <!-- SELECT2 EXAMPLE -->
         <div class="card card-default">
            <div class="card-header">
               <h3 class="card-title">Add new User</h3>
               <div class="card-tools">
                  <button type="button" class="btn btn-tool" data-card-widget="collapse">
                  <i class="fas fa-minus"></i>
                  </button>
                  <button type="button" class="btn btn-tool" data-card-widget="remove">
                  <i class="fas fa-times"></i>
                  </button>
               </div>
            </div>
            <!-- /.card-header -->
            <form method="POST" wire:submit.prevent="storeUser">
               <div class="card-body">
                  <div class="row">
                     <div class="col-md-6">
                        <div class="form-group">
                           <label>Name</label>
                           <input type="text" wire:model.lazy="name" class="form-control  @error('name') is-invalid @enderror">
                           @error('name')
                           <div class="invalid-feedback">
                              {{ $message }}
                           </div>
                           @enderror
                        </div>
                     </div>
                     <div class="col-md-6">
                        <div class="form-group">
                           <label>Email</label>
                           <input type="text"  wire:model.lazy="email" class="form-control  @error('email') is-invalid @enderror">
                           @error('email') <span class="text-danger">{{ $message }}</span>@enderror
                        </div>
                     </div>
                     <div class="col-md-6">
                        <div class="form-group">
                           <label>Phone</label>
                           <input type="text"  wire:model.lazy="phone"  class="form-control  @error('phone') is-invalid @enderror">
                           @error('phone')
                           <div class="invalid-feedback">
                              {{ $message }}
                           </div>
                           @enderror
                        </div>
                     </div>
                     <div class="col-md-6">
                        <div class="form-group">
                           <label>Address</label>
                           <input type="text"  wire:model.lazy="address"  class="form-control  @error('address') is-invalid @enderror">
                           @error('address')
                           <div class="invalid-feedback">
                              {{ $message }}
                           </div>
                           @enderror
                        </div>
                     </div>
                  </div>
                  <div>
                     <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                     <button type="submit" class="btn btn-primary">Save</button>
                  </div>
            </form>
            <!-- /.card -->
            </div>
         </div>
         <!-- /.row -->
      </div>
   </section>
</div>

Syntax:

<div class="form-group">
      <label>Email</label>
      <input type="text" wire:model.lazy="email" class="form-control  @error('email') is-invalid @enderror">
      @error('email') <span class="text-danger">{{ $message }}</span>@enderror
</div>

Livewire custom validation messages

Livewire offers various convenient validation rules that can be applied to the data if values are specific to a database table. In this insightful article, we will cover some of the validation rules.

app\Http\Livewire\RealTimeValidationExample.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\Validator;
use App\Models\RealTimeVal;

class RealTimeValidationExample extends Component
{

    public $name;
    public $email;
    public $phone ;
    public $address;

    protected $rules = [
        'name'  => 'required',
        'email' => 'required|email',
        'phone' => 'required|numeric',
        'address' => 'required',
    ];
   
    protected $messages = [
        'email.required'   => 'The Email Address cannot be empty.',
        'email.email'        => 'The Email Address format is not valid.',
        'phone.required' => 'The Phone Number cannot be empty.',
        'phone.numeric'  => 'The Phone Number format is not valid.',
    ];
    
    public function updated($propertyName)
    {
        $this->validateOnly($propertyName);
    }

    public function storeUser()
    {
        $validatedData = $this->validate();
 
        RealTimeVal::create($validatedData);

       $this->reset(['name', 'email', 'phone', 'address']);
    }
    
    public function render()
    {
        return view('livewire.real-time-validation-example');
    }
}

Livewire reset validation

$this->reset(['name', 'email', 'phone', 'address']);

In this article, we learned “Larvel Livewire Real-time Validation with Livewire custom validation messages”, I hope this article will help you with your Laravel application Project.

reset validation in laravel livewire

Read also:- Retain old form data on validation error in Laravel.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com

Scroll to Top