Forms are an integral part of web applications. It allows users to input data and interact with your website. Whether it’s for user registration, login, or simply providing feedback. However, poorly handled form submissions can result in a frustrating user experience. There are different ways to handle the form validation. Such is through every form submitted, or through real-time form validation. One way to enhance the user experience is through real-time form validation. It provides instant feedback to users as they fill out the form. In this tutorial, we will explore how to achieve this using Laravel Livewire. Laravel Livewire form validation provides an easy way to handle form submission requests. This is a powerful library for building dynamic web interfaces. If you are an absolute beginner in Livewire, then you can follow the Getting Started with Laravel Livewire.
What is Livewire?
Livewire is a full-stack framework for Laravel that enables developers to build dynamic web interfaces without writing a single line of JavaScript. It simplifies the development process by allowing you to write your front-end logic using PHP and Blade templates. You can use the different form validation techniques. The real-time form interactivity is typically associated with JavaScript frameworks.
Before moving to this example, let’s take a glimpse of the demo application that we are going to build in this post.
Now, let’s implement the Laravel Livewire form validation.
Prerequisites
Before diving into Livewire form validation, make sure you have the following prerequisites in place:
- Laravel: You should have Laravel installed on your local development environment. If not, then create a new project for this.
- Composer: Ensure that composer is installed on your system as it’s required for managing Laravel packages.
- Basic Understanding: Familiarity with Laravel and Blade templates will be helpful.
Recommended: Scaling Laravel Apps with Efficient Many-to-Many Relationships
Step 1 – Create a Laravel Project
If you don’t already have a Laravel project, you can create one by running the following command in your terminal.
composer create-project --prefer-dist laravel/laravel livewire-form
It will take a couple of seconds to install. Hence, once you have done so, let’s proceed with the livewire installation in Laravel.
So, next, just navigate to the project directory.
cd livewire-form
Thereafter, we will be installing Livewire in Laravel.
Step 2 – Install Livewire in Laravel For Form Validation
To install the Laravel Livewire package, you will have to hit the below command.
composer require livewire/livewire
This command installs Livewire and its dependencies into your Laravel project.
Step 3 – Create a Livewire Component for Livewire form Validation
In order to go ahead with livewire form validation, you required a Livewire component. Hence, you can create it using the below command.
php artisan make:livewire ContactForm
Here, the command will create a component having two files. The one will be a class file and another will be a blade (view) file.
The class file will be located in the app/Http/Livewire
directory. If you open that then you will have the below snippet inside it.
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class ContactForm extends Component
{
public function render()
{
return view('livewire.contact-form');
}
}
But, the blade file will be located in the resources/views/livewire
directory. This will contain an empty div by default as shown below.
<div>
{{-- Close your eyes. Count to one. That is how long forever feels. --}}
</div>
Now, it’s time to design a basic form in which we can apply the Livewire form validation.
Recommended: Advanced Eloquent Relation with hasManyThrough in Laravel 10
Step 4 – Design a Form to Apply Livewire Form Validation
At the very first, open the contact-form.blade file available in the resources/views/livewire
directory. Thereafter, you will have to add the below snippet for a basic form.
<div class="container my-2">
<div class="row">
<div class="col-xl-6 m-auto">
{{-- form starts --}}
<form>
<div class="card shadow">
<div class="card-header">
<h4 class="card-title fw-bold">Livewire Form Validation </h4>
</div>
<div class="card-body">
{{-- name --}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name" class="form-control">
</div>
{{-- email --}}
<div class="form-group my-3">
<label for="email">Email</label>
<input type="email" id="email" placeholder="Email" class="form-control">
</div>
{{-- message --}}
<div class="form-group my-3">
<label for="message">Message</label>
<textarea id="message" placeholder="Message" class="form-control"></textarea>
</div>
<div class="form-group mb-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
{{-- form ends --}}
</div>
</div>
</div>
I have designed a very basic form to apply the livewire validation over here. Now, let’s include this component in a Laravel blade file.
Step 5 – Include Livewire Component in Laravel Blade
To include this Livewire form component, I will create a fresh blade file with the name master.blade.php. That will contain the Bootstrap for applying some inbuilt styles.
Therefore, I have created a master blade file and included the Livewire (ContactForm) component.
<!doctype html>
<html lang="en">
<head>
<title>Livewire Form Validation in Laravel</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS v5.2.1 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
<!-- Livewire Style -->
@livewireStyles
</head>
<body>
<main>
<!-- Include Livewire Component -->
@livewire('contact-form')
</main>
<!-- Livewire Scripts -->
@livewireScripts
</body>
</html>
Now, I have created a route to render this master blade file in order to see the form design.
Route::get('/form', function() {
return view('master');
});
Now, if you run the application and access the above URL in the browser then you will have the below result.
Next, you will have to handle the form data in order to validate it. So, let’s do it.
Step 6 – Data Binding, Form Handling, and Form Validation in Livewire
So, at very first you will have to capture the inputs from the form. Hence, to achieve this, Livewire provides a data binding feature through which you can read out the form inputs.
Also, the form needs to be submitted. Hence, for this, Livewire provides a form submit event for handling form submission.
The syntax is shown below.
wire:model="inputName" // for capturing input value
wire:submit="YourFunctionName" // for handling form submit
wire:submit.prevent="YourFunctionName" // for handling form submit without refresh
Here, as per the form we have created, you have to add the data binding property in each input except the button. Hence, let’s do that quickly.
<div class="container my-2">
<div class="row">
<div class="col-xl-6 m-auto">
{{-- form starts --}}
<form wire:submit.prevent="submitForm">
<div class="card shadow">
<div class="card-header">
<h4 class="card-title fw-bold">Livewire Form Validation </h4>
</div>
<div class="card-body">
{{-- name --}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" wire:model="name" placeholder="Name" class="form-control">
</div>
{{-- email --}}
<div class="form-group my-3">
<label for="email">Email</label>
<input type="text" id="email" wire:model="email" placeholder="Email" class="form-control">
</div>
{{-- message --}}
<div class="form-group my-3">
<label for="message">Message</label>
<textarea id="message" wire:model="message" placeholder="Message" class="form-control"></textarea>
</div>
<div class="form-group mb-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
{{-- form ends --}}
</div>
</div>
</div>
Now, in order to handle the form submit event and validation, you will have to create the functionality in its respective php file (component).
After adding the form-handling event, the Component class will become as shown below.
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class ContactForm extends Component
{
// Define form input properties
public $name, $email, $message;
public function render()
{
return view('livewire.contact-form');
}
// Form Submit Function
public function submitForm() {
// Form validation rules
$this->validate([
'name' => 'required|min:5',
'email' => 'required|email',
'message' => 'required|min:10|max:100'
]);
}
}
Here, in the submit function, I have defined the validation rules for the inputs. You can refer to the Laravel form Validation for more rules.
After defining the form validation rule, you will have to display the validation error messages across each input field.
Hence, let’s do that in the component view.
Step 7 – Display Validation Error Messages in Livewire Component
The validation error message can be displayed in the same way as you do in Laravel Blade. The syntax is below.
@error('inputName')
<span class="text-danger">{{ $message }}</span>
@enderror
So, let’s add this validation error message next to all inputs.
<div class="container my-2">
<div class="row">
<div class="col-xl-6 m-auto">
{{-- form starts --}}
<form wire:submit.prevent="submitForm">
<div class="card shadow">
<div class="card-header">
<h4 class="card-title fw-bold">Livewire Form Validation </h4>
</div>
<div class="card-body">
{{-- name --}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" wire:model="name" placeholder="Name" aria-describedby="name-error" aria-required="true" @error('name') aria-invalid="true" @enderror class="form-control @error('name') is-invalid @enderror">
{{-- Display name validation error message --}}
@error('name')
<span id="name-error" class="text-danger">{{ $message }}</span>
@enderror
</div>
{{-- email --}}
<div class="form-group my-3">
<label for="email">Email</label>
<input type="text" id="email" wire:model="email" placeholder="Email" aria-describedby="email-error" @error('email') aria-invalid="true" @enderror class="form-control @error('email') is-invalid @enderror">
{{-- Display email validation error message --}}
@error('email')
<span id="email-error" class="text-danger">{{ $message }}</span>
@enderror
</div>
{{-- message --}}
<div class="form-group my-3">
<label for="message">Message</label>
<textarea id="message" wire:model="message" placeholder="Message" aria-describedby="message-error" @error('message') aria-invalid="true" @enderror class="form-control @error('message') is-invalid @enderror"></textarea>
{{-- Display message validation error message --}}
@error('message')
<span id="message-error" class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group mb-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
{{-- form ends --}}
</div>
</div>
</div>
Now, refresh the browser and submit the form to check the validation error message.
So, you can see the validation is applied to the form submit event. Now, let’s move to the customization and other things regarding validation.
You can customize the error messages instead of the default one in Livewire similar to Laravel.
Customize Validation Error Messages in Livewire
You can put custom validation error messages in the same validation error array. Take a look at the below snippet.
// Form Submit Function
public function submitForm() {
// Form validation rules
$this->validate([
'name' => 'required|min:5',
'email' => 'required|email',
'message' => 'required|min:10|max:100'
], [
'name.required' => 'Please enter your name',
'name.min' => 'Name must be atleast 5 chars',
'email' => 'Please enter your email address',
'email.email' => 'Please enter a valid email address',
'message.reqired' => 'Please enter your message',
'message.min' => 'Message must be atleast 10 chars',
'message.max' => 'Message must be max 100 chars',
]);
}
Now, in the response, you will get the custom error messages.
You can check the min, max, and other attribute messages as well.
Create Livewire Form Validation in Rules Property
You can set validation rules in the Laravel rules attribute. This will be very helpful when you will have a large set of inputs to validate. This can be defined outside of the submit function. But, you need to call validate function inside the form submit function.
// Form Validation Rules
protected $rules = [
'name' => 'required|min:5',
'email' => 'required|email',
'message' => 'required|min:10|max:100'
];
The rules attribute is recommended with protected access specifier. However, you can define it using public property as well.
Now, you will have to call a default validate() function inside the form submit function.
// Form Submit Function
public function submitForm() {
$this->validate();
}
This will work in the same way. This is more clean and a good practice. Even this can be reusable in case you have to use it multiple times.
Similarly, for this rule attributes, you can define the custom error messages using the messages property.
// Set Custom Error Messages
protected $messages = [
'name.required' => 'Please enter your name',
'name.min' => 'Name must be atleast 5 chars',
'email' => 'Please enter your email address',
'email.email' => 'Please enter a valid email address',
'message.reqired' => 'Please enter your message',
'message.min' => 'Message must be atleast 10 chars',
'message.max' => 'Message must be max 100 chars',
];
So, in the result, you will get the custom error messages in the validation error response.
Laravel Livewire form validation provides real-time form validation as well. So, let’s see how you can do that.
Livewire Realtime Form Validation
One of the best features of Livewire is the real-time form validation. To handle real-time form validation, Livewire provides the updated
method. This method is called whenever a Livewire property is updated. In your ContactForm.php
component, add the updated
method to trigger real-time validation.
You have nothing to change in the validation rules. The below function will trigger immediately when you will start typing something in inputs.
// Real Time Form Validation
public function updated($propertyName)
{
$this->validateOnly($propertyName);
}
The result will be like this. Here, you don’t need to click on the submit button. Just start typing in the inputs and it will invoke the validation rules automatically.
Conclusion
In conclusion, Livewire provides different ways to validate the form. You can customize the error message and set different validation rules. The real-time form validation with Laravel Livewire is a powerful technique that greatly enhances the user experience of your web applications. This step-by-step guide has walked you through the process of implementing form validation with Livewire, from creating a Livewire component to handling real-time validation and displaying error messages. I hope this post will help you.
Leave a Reply