LARAVEL Tutorial


Form Validation Using JQuery In Laravel 7/6

Author:- w3alert.com
Updated Date:-11-08-2020

In this tutorial, you will learn how to validate form data on the client-side (before submitting the form) using jquery in laravel web applications. And also learn how to validate form fields or data without refresh the whole web page.

Here, you will also learn how to validate form data on the server-side (on the controller) and client-side ( without refresh whole page).  In laravel, Server-side validation always works and then insert or update form data into MySQL database tables.

In this tutorial, we will create a contact us form and use jQuery validation rules for validating form data. And also insert form data into the database. Below we will provide the downloading link for this laravel jQuery form validation web application. You can use this link and download it.

Laravel jQuery Form Validation Example Tutorial

  • Install Laravel Application
  • Configure Database Detail
  • Create Model and Migration
  • Run Migration
  • Create Routes
  • Generate Controller By Artisan
  • Create Blade View
  • Start Development Server

Install Laravel Application

First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:

composer create-project laravel/laravel FormValidation –-prefer-dist

If you want to install a specific version of laravel, you can follow the following tutorial

https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer

Configure Database Detail

After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=root

Create Model and Migration

Next, we need to create a model and migration in your laravel web application using the php artisan make:model model_name -m. So run the following command in your project root directory.

Go to the command prompt

cd/project_root_directory

php artisan make:model Contact -m

after that, go to database/migrations/ and find created migration file and add fields, as you want to in your database table.

Your migration file looks like:

<?php

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

class CreateContactsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->text('message');
            $table->timestamps();
        });
    }

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

And go to the app/ directory and find the model file. And add table field name as fillable property:- protected $fillable = ['name', 'email', 'message']; 

Your model file looks like:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    protected $fillable = ['name', 'email', 'message']; 
}

Run Migration

Before you will run php artisan migrate command. Go to app/providers/AppServiceProvider.php and update the below code :

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

Next, go to command prompt and run the following command:

php artisan migrate
OR
php artisan migrate:fresh

This php artisan migrate command creates a table in your database.

Create Routes

Next step, go to routes/web.php file and update the following routes into your file:

//display contact us form
Route::get('contact-us','[email protected]');

//insert contact us data into mysql database table laravel
Route::post('save-contact','[email protected]');

Generate Controller By Artisan

Now, you need to generate a controller file, so use the php artisan make:controller command and generate/create a new controller file:

php artisan make:controller ContactFormController

In this controller file, we will create 2 methods for display jquery validation form and store form data into MySQL database table in laravel web application.

After that, go to App/Http/Controllers/ directory and find the created ContactFormController file and update the following code into your file:

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Validator,Redirect,Response;
Use App\Contact;
 
class ContactFormController extends Controller
{
    public function index() {
        return view('contact');
    }
 
    public function store(Request $request)
    {
        request()->validate([
            'name' => 'required',
            'email' => 'required|email',
            'message' => 'required',
        ]);
       
         $check = Contact::create($request->all());

         return Redirect::to("contact-us")->withSuccess('Form successfully submit');
 
    }
}

Create Blade Views

Next, you need to create a blade views file, so go resource/views directory and create the following blade views file.

Go to resource/views/ then create a new file name contact.blade.php and update the following code:

<!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 Jquery Form Validation Example - w3alert.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  <script src="//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 mt-5">
 
    @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="contact-us-form" method="post" action="{{url('save-contact')}}">
      @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="message">Message</label>
        <textarea name="message" class="form-control" id="message" placeholder="Please enter message"></textarea>
        <span class="text-danger">{{ $errors->first('message') }}</span>
      </div>

      <div class="form-group">
       <button type="submit" class="btn btn-success">Submit</button>
      </div>
    </form>
 
</div>
<script>
   if ($("#contact-us-form").length > 0) {
    $("#contact-us-form").validate({
     
    rules: {
      name: {
        required: true,
        maxlength: 50
      },
 
      email: {
        required: true,
        maxlength: 50,
        email: true,
      },  

      message: {
        required: true,
        minlength: 50,
        maxlength: 200,
      },    
    },
    messages: {
       
      name: {
        required: "Please enter name",
        maxlength: "Your last name maxlength should be 50 characters long."
      },

      email: {
          required: "Please enter valid email",
          email: "Please enter valid email",
          maxlength: "The email name should less than or equal to 50 characters",
      },      

      message: {
          required: "Please enter message",
          minlength: "The message should be accept minimum 50 characters",
          maxlength: "The message should be accept minimum 50 characters",
      },
        
    },
    })
  }
</script>
</body>
</html>

In contact.blade.php file, we have included jQuery form validation libraries in the header and also written the jQuery validation rules in the footer.

Start development server

You can use the following command artisan command to start the development server:

php artisan serve

The final step, go to your browser and type the below-given URL into your browser:

http://localhost:8000/contact-us
OR

http://localhost/FormValidation/public/contact-us

You can also download laravel jquery form validation web application here Download

Reference

This tutorial idea has taken from the following urls: