Laravel 7/6 jQuery Form Validation Example

Laravel 7/6 jQuery Form Validation Example

Here you will learn how you can add jquery validation in laravel forms and as well as how to add jquery custom error message in laravel forms.

First of all, create a laravel form then add jquery validation with a custom error message.

Laravel jQuery Form Validation Example

Follow the below steps and add jQuery validation with custom error messages in laravel 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, we need to download the laravel fresh setup. Use the below command and 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. It will create one model also with one migration file.

 php artisan model Contact -m 

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

   public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->text('message');
            $table->timestamps();
        });
    }

Before we 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/Contact.php file and add the fillable properties like this :

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

Step 4: Make Route

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

 Route::get('form-jquery', 'ContactController@index');
Route::post('store', 'ContactController@store');

Step 5: Create Controller

In this step, We need to create a controller name ContactController. Use the below command and create Controller :

php artisan make:controller ContactController 

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

<?php
namespace App\Http\Controllers;

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

class ContactController extends Controller
{

    public function index()
    {
      return view('contact');
    }

    public function store(Request $request)
    {
        $data = request()->validate([
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required'
        ]);
       
        $check = Contact::create($data);
        return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
    }
}

Step 6: Create Blade view

In this step, we need to create a blade view file. Go to app/resources/views and create one file name contact.blade.php.

<html>
   <head>
      <title>Laravel Jquery Form Validation From Scratch</title>
      <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
      <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
      <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>
   </head>
   <style type="text/css">
      body{
      background-color: #25274d;
      }
      .contact{
      padding: 4%;
      height: 400px;
      }
      .col-md-3{
      background: #ff9b00;
      padding: 4%;
      border-top-left-radius: 0.5rem;
      border-bottom-left-radius: 0.5rem;
      }
      .contact-info{
      margin-top:10%;
      }
      .contact-info img{
      margin-bottom: 15%;
      }
      .contact-info h2{
      margin-bottom: 10%;
      }
      .col-md-9{
      background: #fff;
      padding: 3%;
      border-top-right-radius: 0.5rem;
      border-bottom-right-radius: 0.5rem;
      }
      .contact-form label{
      font-weight:600;
      }
      .contact-form button{
      background: #25274d;
      color: #fff;
      font-weight: 600;
      width: 25%;
      }
      .contact-form button:focus{
      box-shadow:none;
      }
   </style>
   <body>
      <div class="container contact">
         <br><br><br>
         <div class="row">
            <div class="col-md-3">
               <div class="contact-info">
                  <img src="{{ url('public/images/1553741491contact-image.png') }}" alt="image"/>
                  <h2>Contact Us</h2>
                  <h4>We would love to hear from you !</h4>
               </div>
            </div>
            <div class="col-md-9">
               @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 action="{{ url('store') }}" method="post" accept-charset="utf-8" id="contact_form">
                  @csrf
                  <div class="contact-form">
                     <div class="form-group">
                        <label class="control-label col-sm-2" for="fname">First Name:</label>
                        <div class="col-sm-10">          
                           <input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
                           <span class="text-danger">{{ $errors->first('name') }}</span>
                        </div>
                     </div>
                     <div class="form-group">
                        <label class="control-label col-sm-2" for="email">Email:</label>
                        <div class="col-sm-10">
                           <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
                           <span class="text-danger">{{ $errors->first('email') }}</span>
                        </div>
                     </div>
                     <div class="form-group">
                        <label class="control-label col-sm-2" for="comment">Comment:</label>
                        <div class="col-sm-10">
                           <textarea class="form-control" rows="5" name="message" id="message"></textarea>
                           <span class="text-danger">{{ $errors->first('message') }}</span>
                        </div>
                     </div>
                     <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                           <button type="submit" class="btn btn-default">Submit</button>
                        </div>
                     </div>
                  </div>
               </form>
            </div>
         </div>
         <br><br><br><br>
      </div>
   </body>

   <script>
    if ($("#contact_form").length > 0) {
        $("#contact_form").validate({

            rules: {
                name: {
                    required: true,
                    maxlength: 50
                },

                email: {
                    required: true,
                    maxlength: 50,
                    email: true,
                },

                message: {
                    required: true,
                    minlength: 50,
                    maxlength: 500,
                },
            },
            messages: {

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

            },
        })
    } 
 </script>
</html>

Step 7: Run Development Server

In this step, We need to start the development server. Use the php artisan serve command and start your 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 7/6 application using jquery validation. Also, we have sent validate form data to the server.

You may like

  1. Laravel Google ReCaptcha Form Validation
  2. Form Validation Example In Laravel
  3. Laravel Ajax Form Submit With Validation Tutorial

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

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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