Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Laravel 8 ajax form validation

Laravel 8 Ajax form validation with example

Aman Jain, October 20, 2021November 16, 2021

In this article, I will demonstrate to show Laravel server side validation using Ajax. We will use jQuery to show the validation and submit the form. Using the jQuery and AJAX we will prevent the page reloading and show the validation. In this article, we will use the same simple form and controller but the only thing we need to change is the response method which will be JSON.

Also read Laravel 8 form validation with example.

Let’s begin the tutorial of Laravel Ajax Form Validation Online in simple steps:

Step 1: Create Laravel project

First step is to create the Laravel 8 project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations

composer create-project laravel/laravel example-app

Step 2: Create controller

Now, create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.

php artisan make:controller PostController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{

     /**
     * Show the form to create a new blog post.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Store a new blog post.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',   // required and email format validation
            'phone_number' => 'required|numeric|digits_between:9,15', // required and number field validation
            'username' => ['required'],
        ]); // create the validations
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {
            
            return response()->json($validator->errors(),422);
            //return back()->withInput()->withErrors($validator);
            // validation failed return the json
        }
        else
        {
            return response()->json(["status"=>true,"message"=>"Form submitted successfully"]);
        }  
    }
     
}

Here , we added two methods one for to show the form view(create) and store to handle the form submit and validation.

Next, we have added validation for email, phone number and username. Email is required and should be format of email. Then, phone number should be required, numeric , digit_between 9 to 15.

Step 3: Create blade file for view

Now it’s time to show the form and validation message to our view, so let’s create the view file.

 <h3>Laravel 8 custom form validation - Readerstacks</h3>

            <form method="post" id="validateajax" action="{{url('submit-post')}}" name="registerform">
              <div class="form-group">
                <label>Email</label>
                <input type="text" name="email" value="{{ old('email') }}" class="@error('email') is-invalid @enderror form-control" />

                @error('email')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
                @csrf
              </div>
              <div class="form-group">
                <label>Phone number</label>
                <input type="text" name="phone_number" value="{{ old('phone_number') }}" class="@error('phone_number') is-invalid @enderror form-control" />
                @error('phone_number')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
              </div>
              <div class="form-group">
                <label>Username</label>
                <input type="text" name="username" value="{{ old('username') }}" class="@error('username') is-invalid @enderror form-control" />
                @error('username')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
              </div>

              <div class="form-group">
                <button class="btn btn-primary">Register</button>
              </div>
            </form>

Step 4: Add jQuery to handle the form submit

Here is the main logic to handle the form submit using jquery. In this step we will handle form submit using the query post method.

  <script>
    $(function() {
      ("#validateajax").on("submit", function() {

          var action = $(this).attr("action");
          var method = $(this).attr("method");
          if (method == "post") {
            $.post(action, $(this).serialize(), function(data) {
              alert("Form submitted successfully")
            }).fail(function(response) {
              $(".alert").remove();
              var erroJson = JSON.parse(response.responseText);
              for (var err in erroJson) {
                for (var errstr of erroJson[err])
                  $("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
              }

            });;
          }
          return false;

        });
    });

     
  </script>

Here, we added ("#validateajax").on("submit", function() {} to handle the submit event of form. Then, create a post request using $.post and also get the value of form action.

In next line we are handling the fail and success state. if the AJAX failed then it come into the fail block (Http response code 422). if the response code is 200 then it will come into success block.

              $(".alert").remove();
              var erroJson = JSON.parse(response.responseText);
              for (var err in erroJson) {
                for (var errstr of erroJson[err])
                  $("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
              }

Above code we are using to show the validation message below the each field.

Step 5: Create routes

Now, open the routes/web.php and add below routes

<?php

use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\PostController;
use \App\Http\Controllers\QRController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/create-post',[PostController::class, 'create']);
Route::post('/submit-post',[PostController::class, 'store']);
  • Screenshot 2021 10 20 at 12.00.18 AM
    Laravel 8 ajax form validation
  • Screenshot 2021 10 20 at 12.01.08 AM
Laravel 8 json response

Related

Php Laravel

Post navigation

Previous post
Next post

Related Posts

Php A Complete guide to Laravel 8 response

A Complete guide to Laravel 8 response

December 1, 2021November 5, 2023

In this tutorial we will learn about the Laravel response. Laravel has its own library to handle the http response of the application to browser. In the most of the cases response() method is used to send the response back to browser and class Illuminate\Http\Response is also used for same…

Read More
Php Laravel CRUD with Search, Image and Pagination

Laravel 10 CRUD Example Tutorial with Search, Image and Pagination

March 12, 2023July 3, 2024

This article will cover the implementation of CRUD operations along with Search, Image uploading, and Pagination in Laravel. In addition to CRUD operations, we will also cover form validation, unique validation, Flash messages, and viewing uploaded images. It is crucial to learn all aspects of CRUD and beyond, including uploading…

Read More
Php install laravel composer

How to install laravel 8 ?

September 20, 2021May 6, 2022

Laravel is most popular framework of PHP. It provides lots of in-build tools and library to build the web application. Laravel is used to to create robust custom web applications with ease of amazing developer experience. Laravel is easily customizable and provides tools like ORM, Validation libraries, Queue, Mail, Routing,…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version