In this tutorial, we'll explore how to perform AJAX form validation in Laravel 10. We'll create a simple Bootstrap modal containing a form with basic inputs. When the form is submitted, we'll validate it without refreshing the page. In this article, we'll validate the modal popup form using Ajax in laravel 9 and laravel 10.
So, let's see how to validate form using Ajax in laravel 10, laravel 10 form validation using Ajax jQuery, validate Ajax form in laravel 8/9/10, and how to validate modal popup form in laravel.
Firstly, let's install Laravel 10 using the following command:
composer create-project laravel/laravel laravel_10_ajax_form_validation
Next, we'll create a migration and model for our user data. Run the following commands:
php artisan make:migration create_users_table
Migration file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
Then, migrate the table:
php artisan migrate
Now, create the User model:
php artisan make:model User
Generate a UserController using the command:
php artisan make:controller UserController
UserController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users = User::get();
return view('index', compact('users'));
}
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
], [
'name.required' => 'Name field is required.',
'email.required' => 'Email field is required.',
'email.email' => 'Email field must be a valid email address.',
]);
$user = User::create($validatedData);
return response()->json(['success' => 'User created successfully.']);
}
}
Add routes to web.php:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('index', 'index');
Route::post('store', 'store')->name('store');
});
Create an index.blade.php file with the following content:
<!DOCTYPE html>
<html>
<head>
<title>how to validate form using ajax in laravel - vidvatek</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/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>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>
<div class="container">
<div class="card bg-light mt-3">
<div class="card-header">
<strong>how to validate form using ajax in laravel - vidvatek</strong>
</div>
<div class="card-body">
<table class="table table-bordered mt-3">
<tr>
<th colspan="3">
List Of Users
<button type="button" class="btn btn-success float-end" data-bs-toggle="modal" data-bs-target="#userModal">
Create User
</button>
</th>
</tr>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</table>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="ajax-form" action="{{ route('store') }}">
@csrf
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="mb-3">
<label for="name" class="form-label">Name:</label>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
<div class="mb-3">
<label for="email" class="form-label">Email:</label>
<input type="text" name="email" class="form-control" placeholder="Email">
</div>
<div class="mb-3 text-center">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$('#ajax-form').submit(function(e) {
e.preventDefault();
var url = $(this).attr("action");
let formData = new FormData(this);
$.ajax({
type:'POST',
url: url,
data: formData,
contentType: false,
processData: false,
success: (response) => {
alert('Form submitted successfully');
location.reload();
},
error: function(response){
$('#ajax-form').find(".print-error-msg").find("ul").html('');
$('#ajax-form').find(".print-error-msg").css('display','block');
$.each( response.responseJSON.errors, function( key, value ) {
$('#ajax-form').find(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
});
</script>
Finally, run your Laravel 10 application:
php artisan serve
In this tutorial, we've learned how to implement AJAX form validation in Laravel 10.
You might also like:
- Read Also: How to Validate Form in Laravel 10
- Read Also: How to Create Autocomplete Search in Vue JS
- Read Also: Laravel 10 AJAX CRUD Operations With Popup Modal
- Read Also: Laravel 10 Password and Confirm Password Validation