Saturday 31 August 2019

Front-end Form Validation using Parsleys.js in Laravel 5.8



Do you know why Form Validation is needed? This is because Validation of Form Data is required for prevent web application form entered invalid users data. If we have not perform form validation, then it will increase the our system security vulnerabilities. And there is increase the chances of attack of header injection, SQL injections or cross-site scripting.

Now What is Form validation, Form Validation means the check input data which has been submitted by the users of our system. There are two ways we can perform Form validation. One is Client Side Form validation and another one is server side Form Validation.

Here we have use Laravel 5.8 framework for web development. And here we will learn How can we validate user entered input data in our Laravel application at client side. For Validate users input data at client side, for this we have use Parsleys.js javascript library.

Parsley is the Javascript form validation library. By using this javascript library we can perform form validation at frontend that means it will validate form input data at client machine, if all input data has been valid then after it will send this data to server for do database operation. In this tutorial, we will seen how can we use Parsley.js library for client-side form validation in Laravel 5.8 application. Below you can find step by step process for validate form data in Laravel 5.8 application.

  • Download and Install Laravel 5.8 Framework
  • Make Database Connection in Laravel 5.8
  • Create Controller in Laravel 5.8
  • Create View Blade File in Laravel 5.8
  • Set Route in Laravel 5.8
  • Run Laravel 5.8 Application


Download and Install Laravel 5.8 Framework


If you has use Laravel for your Web Development, then first you have to download and install Laravel 5.8 application. For this you have to go to command prompt. And in command prompt first you have to go folder in which you want to download and install Laravel 5.8 framework. After this you have to run "composer" command, because Compose has maintain the laravel package. And after this you have write below command, it will download and install Laravel latest version in your local computer.


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


Make Database Connection in Laravel 5.8


After downloading and installing of Laravel framework, now we want to make database connection. For we have to open .env file and in this file we have to define Mysql Database configuration.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Once you have make Mysql Database connection, now you have to make table in your Database, for this you have run following sql script. This script will make tbl_register table in your Mysql Database.


--
-- Table structure for table `tbl_register`
--

CREATE TABLE `tbl_register` (
  `register_id` int(11) NOT NULL,
  `first_name` varchar(150) NOT NULL,
  `last_name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL,
  `website` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `tbl_register`
--
ALTER TABLE `tbl_register`
  ADD PRIMARY KEY (`register_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_register`
--
ALTER TABLE `tbl_register`
  MODIFY `register_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


Create Controller in Laravel 5.8


In Larave framework, you have to make controller for handle http reqest. In Laravel controller class has been store in app/Http/Controllers and here we have to make FormValidationController.php file. In controller we have write user DB; statement for perform Database side operation. Here we have make following method in controller.

index() - This is the root method of this Form Validation controller. It will load form_validation.blade.php file in browser for display output.

insert(Request $request) - This method has been used for insert data into Mysql table. This method has been received Ajax request from blade file for insert data and this method has give response to Ajax request in json format.

app/Http/Controllers/FormValidationController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;

class FormValidationController extends Controller
{
    function index()
    {
     return view('form_validation');
    }

    function insert(Request $request)
    {
     if(request()->ajax())
     {
      $data = array(
       'first_name' => $request->get('first_name'),
       'last_name'  => $request->get('last_name'),
       'email'   => $request->get('email'),
       'password'  => $request->get('password'),
       'website'  => $request->get('website')
      );

      DB::table('tbl_register')->insert($data);

      return response()->json(['success' => 'Data Added']);
     }
    }
}



Create View Blade File in Laravel 5.8


Now we have come to main part of this tutorial. Here we have to make View Blade file in Laravel 5.8 framework, this file has been used for display html output file on web page. This file has been store in resources/view file. And here we have to make form_validation.blade.php file.

In this file we have imported jQuery Library, Bootstrap library and for form validation we have use Parsley.js javascript library also. For use Parsley.js library, you have to first import jQuery library also. Without jQuery library we cannot use Parsley.js library.Here we have make simple Registration form for perform form validation by using Parsley.js library. Below you can find parsley.js attribute which has been used for form validation in this post.



Parsley.js validators Description
required By using this attribute, it will add input file value if required for submit form data.
data-parsley-pattern="[a-zA-Z]+$" It will check input field value has been match with the define regular expression, if value not match it will trigger validation error.
data-parsley-type="email" This will check if input field value is valid email or not. If input field value is invalid email, then it will trigger validation error.
data-parsley-length="[8,16]" This validator check input field value length has been between define range, if length is not between define range then it will trigger error.
data-parsley-equalto="#password" This validator will check this input field value must be equal to value of input field with id password, if value is not match with define input field then it will trigger error.
data-parsley-trigger="keyup" This validator will trigger validation error on key up event.

Below you can find which Parsley.js library method here in this tutorial.

Parsley.js Method Description
$('#validate_form').parsley(); This method will initialize Parsley.js library on define form id.
$('#validate_form').parsley().isValid() This method will return true, if all form data has been proper.
$('#validate_form').parsley().reset(); This method will remove all formatting which has been generated by Parsley.js library.

After validating all form data, it will send Ajax request to Laravel controller insert() method.

resources/views/form_validation.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Client Side Form Validation using Parsleys.js</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="http://parsleyjs.org/dist/parsley.js"></script>
  <style>
  .box
  {
   width:100%;
   max-width:600px;
   background-color:#f9f9f9;
   border:1px solid #ccc;
   border-radius:5px;
   padding:16px;
   margin:0 auto;
  }
  input.parsley-success,
  select.parsley-success,
  textarea.parsley-success {
    color: #468847;
    background-color: #DFF0D8;
    border: 1px solid #D6E9C6;
  }

  input.parsley-error,
  select.parsley-error,
  textarea.parsley-error {
    color: #B94A48;
    background-color: #F2DEDE;
    border: 1px solid #EED3D7;
  }

  .parsley-errors-list {
    margin: 2px 0 3px;
    padding: 0;
    list-style-type: none;
    font-size: 0.9em;
    line-height: 0.9em;
    opacity: 0;

    transition: all .3s ease-in;
    -o-transition: all .3s ease-in;
    -moz-transition: all .3s ease-in;
    -webkit-transition: all .3s ease-in;
  }

  .parsley-errors-list.filled {
    opacity: 1;
  }
  
  .parsley-type, .parsley-required, .parsley-equalto, .parsley-pattern, .parsley-length{
   color:#ff0000;
  }
  
  </style>

 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 - Client Side Form Validation using Parsleys.js</h3>
     <br />
     <div class="box">
    <form id="validate_form">

     @CSRF

     <div class="row">
      <div class="col-xs-6">
       <div class="form-group">
        <label>First Name</label>
        <input type="text" name="first_name" id="first_name" class="form-control" placeholder="Enter First Name" required data-parsley-pattern="[a-zA-Z]+$" data-parsley-trigger="keyup" />
       </div>
      </div>
      <div class="col-xs-6">
       <div class="form-group">
        <label>Last Name</label>
        <input type="text" name="last_name" id="last_name" class="form-control" placeholder="Enter Last Name" required data-parsley-pattern="[a-zA-Z]+$" data-parsley-trigger="keyup" />
       </div>
      </div>
     </div>
     <div class="form-group">
      <label>Email</label>
      <input type="text" name="email" id="email" class="form-control" placeholder="Email" required data-parsley-type="email" data-parsley-trigger="keyup" />
     </div>
     <div class="form-group">
      <label for="password">Password</label>
      <input type="password" name="password" id="password" class="form-control" placeholder="Password" required data-parsley-length="[8,16]" data-parsley-trigger="keyup" />
     </div>
     <div class="form-group">
      <label>Confirm Password</label>
      <input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm Password" required data-parsley-equalto="#password" data-parsley-trigger="keyup" />
     </div>
     <div class="form-group">
      <label>Website</label>
      <input type="text" name="website" id="website" class="form-control" data-parsley-type="url" data-parsley-trigger="keyup" />
     </div>
     <div class="form-group">
      <div class="checkbox">
       <label> <input type="checkbox" name="check_rules" id="check_rules" required />I Accept the Terms & Conditions</label>
      </div>
     </div>
     <div class="form-group">
      <input type="submit" name="submit" id="submit" value="Submit" class="btn btn-success" />
     </div>

    </form>

   </div>
  </div>
 </body>
</html>
<script>
$(document).ready(function(){

 $('#validate_form').parsley();

 $('#validate_form').on('submit', function(event){
  event.preventDefault();

  if($('#validate_form').parsley().isValid())
  {
   $.ajax({
    url: '{{ route("form-validation.insert") }}',
    method:"POST",
    data:$(this).serialize(),
    dataType:"json",
    beforeSend:function()
    {
     $('#submit').attr('disabled', 'disabled');
     $('#submit').val('Submitting...');
    },
    success:function(data)
    {
     $('#validate_form')[0].reset();
     $('#validate_form').parsley().reset();
     $('#submit').attr('disabled', false);
     $('#submit').val('Submit');
     alert(data.success);
    }
   });
  }
 });

});
</script>



Set Route in Laravel 5.8


Once all code is ready, lastly we have to set the route of controller method. For this we have to open routes/web.php file.

routes/web.php

Route::get('form-validation', 'FormValidationController@index');

Route::post('form-validation/insert', 'FormValidationController@insert')->name('form-validation.insert');


Run Laravel 5.8 Application


For run Laravel application, we have to again go to command prompt and write following command.


php artisan serve


This command will start laravel server, it will provide us base url of our Laravel application. For run above tutorial, we have to type following url in your browser.


http://127.0.0.1:8000/form-validation


So, this way we can perform client-side or front-end side form validation by using Parsley.js library in Laravel 5.8 framework without write any line of code.

2 comments:

  1. Sir, parsley validation doesn't work for bootstrap SELECT tag.

    ReplyDelete
  2. Awsome your post and all videos

    ReplyDelete