Simple Laravel 5.7 Form Validation Using Jquery

Jquery form validation example in laravel From Scratch. In this laravel tutorial, we will guide you how to use jquery validation in laravel form easy and simple way. This jquery validation is also work with laravel 5.8 & 5.7 versions.

Every laravel project has many form and diffent diffent type of validation rules required. Before send form data to server, We will validate form data using jquery form validation library. We will share with you some of daily uses validation rules provided by jquery validation library.

Jquery form validation plugin validate form data without a page refresh. Just follow few steps and validate form before submit to server.

Contents

  • Install Laravel App
  • Setup Database
  • Make Route
  • Create Controller & Methods
  • Create Blade View
  • Start Development Server
  • Conclusion

Install Laravel App

First of we need to download laravel fresh setup. Use the below command and download fresh new laravel setup :

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

Setup Database

After successfully install laravel 5.7 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
Make Migration file with Model
php artisan model Customer -m

Next step, Go to app/database/create_customers_table.php and put the below code here :

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCustomersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('mobile_number');
            $table->string('email')->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('customers');
    }
}

Next migrate the table using the below command :

php artisan migrate

Make Route

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

 Route::get('jquery-form', '[email protected]');
Route::post('save', '[email protected]');

Create Controller

We need to create a controller name JqueryFormController. Use the below command and create Controller :

php artisan make:controller JqueryFormController

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

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator,Redirect,Response;
use App\Customer;

class JqueryFormController extends Controller
{

    public function index()
    {
    
        return view('jquery-form');

    }

    public function save(Request $request)
    {

        request()->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'mobile_number' => 'required|unique:users'
        ]);
        
        $data = $request->all();
      
        $check = Customer::create($data);

        return Redirect::to("jquery-form")->withSuccess('Great! Form successfully submit with validation.');

    }
}

Create Blade view

In this step we need to create blade view file. Go to app/resources/views and create one file name jquery-form.blade.php :

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Laravel 5.7 Jquery Form Validation Example - Tutsmake.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
  <style>
   .error{ color:red; } 
  </style>
</head>

<body>

<div class="container">
    <h2 style="margin-top: 10px;">Laravel 5.7 Jquery Form Validation Example - Tutsmake.com</h2>
    <br>
    <br>

    @if ($message = Session::get('success'))
    <div class="alert alert-success alert-block">
        <button type="button" class="close" data-dismiss="alert">×</button>
          <strong>{{ $message }}</strong>
    </div>
    <br>
    @endif
  
    <form id="customerform" method="post" action="{{url('post-jquery-form')}}">
      @csrf
      <div class="form-group">
        <label for="formGroupExampleInput">Name</label>
        <input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
        <span class="text-danger">{{ $errors->first('name') }}</span>
      </div>
      <div class="form-group">
        <label for="email">Email Id</label>
        <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
        <span class="text-danger">{{ $errors->first('email') }}</span>
      </div>      
      <div class="form-group">
        <label for="mobile_number">Mobile Number</label>
        <input type="text" name="mobile_number" class="form-control" id="mobile_number" placeholder="Please enter mobile number">
        <span class="text-danger">{{ $errors->first('mobile_number') }}</span>
      </div>
      <div class="form-group">
       <button type="submit" class="btn btn-success">Submit</button>
      </div>
    </form>

</div>
<script>
   if ($("#customerform").length > 0) {
    $("#customerform").validate({
    
    rules: {
      name: {
        required: true,
        maxlength: 50
      },

       mobile_number: {
            required: true,
            digits:true,
            minlength: 6,
            maxlength:12,
        },
        email: {
                required: true,
                maxlength: 50,
                email: true,
            },    
    },
    messages: {
      
      name: {
        required: "Please enter name",
        maxlength: "Your last name maxlength should be 50 characters long."
      },
      mobile_number: {
        required: "Please enter contact number",
        minlength: "The contact number should be 10 digits",
        digits: "Please enter only numbers",
        maxlength: "The contact number should be 10 digits",
      },
      email: {
          required: "Please enter valid email",
          email: "Please enter valid email",
          maxlength: "The email name should less than or equal to 50 characters",
        },
       
    },
    })
  }
</script>
</body>
</html>

Start Development Server

We need to start development server. Use the php artisan serve command and start your server :

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080  

Now we are ready to run our example so run bellow command to quick run.

 http://localhost:8000/jquery-form
Or direct hit in your browser
http://localhost/JqueryFormValidation/public/jquery-form

Conclusion

In this tutorial , We have successfully validate form data before send to server using jquery form validation plugin in laravel 5.7 application. our examples run quickly.

Laravel 5.7 form validation using jquery example look like this :

form validation using jquery laravel 5.7

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

Spread the love

Be First to Comment

Leave a Reply

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