Laravel 9 jQuery Form Validation Example Tutorial

Laravel 9 jQuery form validation; Through this tutorial, i am going to show you how to form data before send to controller or server using jQuery validation in laravel 9.

Form Validation using jQuery in Laravel 9

Use the below given steps to validate form data using jQuery library in laravel 9 apps:

  • Step 1 – Install Laravel 9 Application
  • Step 2 – Configuring Database using Env File
  • Step 3 – Create Model & Migration File For Product Add Form
  • Step 4 – Create Routes
  • Step 5 – Creating Controller
  • Step 6 – Create Blade File For Product Add Form
  • Step 7 – Start Development Server
  • Step 8 – Run Laravel 9 jQuery Form Validation App On Browser

Step 1 – Install Laravel 9 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel latest application using the following command:

composer create-project --prefer-dist laravel/laravel LaraveljQuery

Step 2 – Configuring Database using Env File

In step 2, open your downloaded laravel app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Create Model & Migration File For Product Add Form

In step 3, open command prompt and navigate to your project by using the following command:

cd / LaraveljQuery

Then create model and migration file by using the following command:

php artisan make:model Product -m

The above command will create two files into your laravel form validation application, which is located inside the following locations:

  • LaraveljQuery/app/Models/Product.php
  • LaraveljQuery/database/migrations/create_products_table.php

So, find create_products_table.php file inside LaravelForm/database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('code');
            $table->text('description');
            $table->timestamps();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;


/*
|--------------------------------------------------------------------------
| 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('/', function () {
    return view('welcome');
});

Route::get('jquery-validation', [ProductController::class, 'index']);
Route::post('store-product', [ProductController::class, 'store']);

Step 5 – Creating Controller

In step 5, create form controller by using the following command:

php artisan make:controller ProductController

The above command will create ProductController.php file, which is located inside LaraveljQuery/app/Http/Controllers/ directory.

The following laravel validation rules will validate form data on server side in laravel:

        $validatedData = $request->validate([
          'title' => 'required|unique:posts|max:255',
          'code' => 'required|unique:posts|max:255',
          'description' => 'required',
        ]);

So open ProductController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;


class ProductController extends Controller
{
    public function index()
    {
        return view('product');
    }

    public function store(Request $request)
    {
        
        $validatedData = $request->validate([
          'title' => 'required|unique:posts|max:255',
          'code' => 'required|unique:posts|max:255',
          'description' => 'required',
        ]);

        $product = new Product;

        $product->title = $request->title;
        $product->code = $request->code;
        $product->description = $request->description;

        $product->save();

        return redirect('jquery-validation')->with('status', 'Product Has Been Added');

    }
}

Step 6 – Create Blade File For Product Add Form

In step 6, create new blade view file that named product.blade.php inside resources/views directory for add add product form.

The following code display error message in laravel forms. So do not forget to add the following code along laravel forms fields:

          @error('title')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror

And the following jQuery code will validate form data on client side or before submit to controller or database:

<script>
    if ($("#product-add").length > 0) {
        $("#product-add").validate({
 
            rules: {
                title: {
                    required: true,
                    maxlength: 50
                },
 
                code: {
                    required: true,
                },
 
                description: {
                    required: true,
                },
            },
            messages: {
 
                title: {
                    required: "Please enter title",
                },

                code: {
                    required: "Please enter valid email",
                },
                
                 description: {
                    required: "Please enter message",
                },
            },
        })
    } 
 </script>

Don’t worry i have already added the jQuery and server side validation error message display code along with each form fields.

So, you can add the following php and html form code into product.blade.php:

<!DOCTYPE html>
<html>
<head>
	<title>Laravel 9 jQuery Validation Example Tutorial</title>
	<meta name="csrf-token" content="{{ csrf_token() }}">

	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>

  <style>
    .error{
     color: #FF0000; 
    }
  </style>

</head>
<body>

<div class="container mt-4">

  @if(session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
  @endif

  <div class="card">
    <div class="card-header text-center font-weight-bold">
      <h2>Laravel 9 jQuery Form Validation Before Submit</h2>
    </div>
    <div class="card-body">
      <form name="product-add" id="product-add" method="post" action="{{url('store-product')}}">
       @csrf

        <div class="form-group">
          <label for="exampleInputEmail1">Title</label>
          <input type="text" id="title" name="title" class="@error('title') is-invalid @enderror form-control">
          @error('title')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
        </div>        

        <div class="form-group">
          <label for="exampleInputEmail1">Product Code</label>
          <input type="text" id="code" name="code" class="@error('code') is-invalid @enderror form-control">
          @error('code')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
        </div>

        <div class="form-group">
          <label for="exampleInputEmail1">Description</label>
          <textarea name="description" class="@error('description') is-invalid @enderror form-control"></textarea>
          @error('description')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
        </div>

        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    </div>
  </div>
</div>	
<script>
    if ($("#product-add").length > 0) {
        $("#product-add").validate({
 
            rules: {
                title: {
                    required: true,
                    maxlength: 50
                },
 
                code: {
                    required: true,
                },
 
                description: {
                    required: true,
                },
            },
            messages: {
 
                title: {
                    required: "Please enter title",
                },

                code: {
                    required: "Please enter valid email",
                },

                 description: {
                    required: "Please enter message",
                },
            },
        })
    } 
 </script>
</body>
</html>

Step 7 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your laravel jquery form validation application:

php artisan serve

Step 8 – Run Laravel 9 jQuery Form Validation App On Browser

In step 8, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/jquery-validation

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *