Ajax form validation and display error messages laravel
Why is validation necessary?
In some times Laravel’s default validation system is efficient then use Ajax form validation.
Ajax form validation is crucial when storing or updating data in our application’s database. It ensures that the data format is correct, prevents the storage of data if any validation criteria are not met, checks if form input fields are empty, and more.
Laravel’s default validation system is efficient and straightforward to implement in any application. However, in today’s tutorial, we’ll explore how to enhance it with jQuery and Ajax to display error messages if validation fails. When validation rules are applied to input fields, the server verifies the input against these rules. If any validation fails, the user is redirected to the creation page with error messages.
Below are the steps to complete the validation process:
- Set up the Laravel project.
- Define routes.
- Create a Blade file within the views directory.
- Implement the controller logic.
- Test the validation and display error messages.
Step -1 : Set up the Laravel project.
There are several ways to set up a Laravel project, but two popular methods are via Composer and the Laravel Installer. Before installing a Laravel project, ensure that you have Composer installed.
composer create-project laravel/laravel ajax-validation
Step- 2. Define routes.
In step 2 we will create two routes one is for return form page and another one is for submit our form.
routes\web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ValidationController;
Route::get('/',[ValidationController::class,'welcome'])->name('welcome');
Route::post('/ajax-form-validate',[ValidationController::class,'ajax_form_validate'])->name('ajax.form.validate');
Step -3 : Create a Blade file within the views directory.
At first let’s design our form with the bellow code
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>{{ 'ajax form validation' }}</title>
</head>
<body>
<div class="container">
<div class="row mt-3">
<div class="col-md-8 offset-md-2">
<div class="card">
<div class="card-header">
<div class="title">
<h3 class="text-left">{{ 'ajax form validation.' }}</h3>
</div>
</div>
<div class="card-body">
<div class="errorMsgntainer"></div>
<form>
@csrf
<div class="row">
<div class="col-md-12">
<div class="mb-3">
<label class="mb-1">{{ 'Your Name' }}</label>
<input type="text" name="name" class="form-control" value="{{ old('name') }}">
</div>
<div class="mb-3">
<label class="mb-1">{{ 'Your Email'}}</label>
<input type="email" name="email" class="form-control" value="{{ old('email') }}">
</div>
</div>
<button type="submit" class="btn btn-primary add-data">{{ 'Submit'}}</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src ="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
<script>
$(document).ready(function(){
//add product
$(document).on('click','.add-data',function(e){
e.preventDefault();
let name = $('#name').val();
let email = $('#email').val();
$.ajax({
method:'post',
url:'{{ route('ajax.form.validate') }}',
data:{name:name,email:email},
success:function(res){
//
},
error:function(err){
let error = err.responseJSON;
$.each(error.errors, function (index, value) {
$('.errorMsgntainer').append('<span class="text-danger">'+value+'<span>'+'<br>');
});
}
});
})
})
</script>
</body>
</html>
Step – 4 :Implement the controller logic.
Type the following command to create controller
php artisan make:controller ValidationController
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ValidationController extends Controller
{
public function welcome()
{
return view('welcome');
}
public function ajax_form_validate(Request $request)
{
$request->validate([
'name'=>'required|regex:/^[\pL\s\-]+$/u|max:50',
'email'=>'required|regex:/(.+)@(.+)\.(.+)/i|email|max:50',
]);
}
}
Step – 5 : Test the validation and display error messages.
Before submitting the form, remember to start the development server by running the following command.
php artisan serve
