Friday, December 27, 2024
Google search engine
HomeLanguagesLaravel 9 Client Side Form Validation Using jQuery

Laravel 9 Client Side Form Validation Using jQuery

form validation using jquery in laravel 9; Through this tutorial, we will learn how to add jquery validation in laravel 9 forms and as well as how to add jquery custom error message in laravel forms.

Laravel 9 Client Side Form Validation Using jQuery

Follow the below steps to add jQuery validation with custom error messages in laravel 9 forms:

  • Step 1: Install Laravel Fresh Setup
  • Step 2: Setup Database
  • Step 3: Make Migration file with Model
  • Step 4: Make Route
  • Step 5: Create Controller & Methods
  • Step 6: Create Blade View
  • Step 7: Start Development Server

Step 1: Install Laravel Fresh Setup

First of all, Execute the following command on terminal to download fresh new laravel setup:

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

Step 2: Setup Database

After successfully install laravel Application, Go to your project .env file and set up database credential and move next step :

 DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

Step 3: Make Migration file with Model

Use the below command to create one model also with one migration file.

 php artisan model Product -m 

Now go to Go to app/database/create_products_table.php and replace the below function :

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

Before run php artisan migrate command go to app/providers/AppServiceProvider.php and put the below code :

..
use Illuminate\Support\Facades\Schema;
 
....
function boot()
{
    Schema::defaultStringLength(191);
}
... 

Next migrate the table using the below command.

php artisan migrate

Now go to app/Product.php file and add the fillable properties like this :

protected $fillable = [ 'name', 'email', 'message', ];

Step 4: Make Route

Create two routes in the web.php file. Go to app/routes/web.php file and create two below routes here :

<?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: Create Controller

Create a controller name ContactController, So run the below command on terminal:

php artisan make:controller ProductController

After successfully create controller go to app/controllers/ProductController.php and put the below code :

<?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:products|max:255',
          'code' => 'required|unique:products|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 view

Create a blade view file. So, Go to app/resources/views and create one file name product.blade.php.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 jQuery Validation Example Tutorial - Tutsmake.com</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 - Tutsmake.com</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: Run Development Server

Run the following command on terminal to start server :

php artisan serve

Now we are ready to run our example, so hit the below url on the browser to quick run.

 http://localhost:8000/form-jquery

Conclusion

In this tutorial, We have successfully validated form data on client-side in laravel 9 application using jquery validation.

Recommended Laravel Tutorials

If you have any questions or thoughts to share, use the comment form below to reach us.

RELATED ARTICLES

Most Popular

Recent Comments