How to Validate Form using Parsleys.js with Laravel 5.8

How to Validate Form using Parsleys.js with Laravel 5.8

In this post, we want to show how to implement client Side Form validation in Laravel 5.8 using Parsleys.js javascript library.

Originally published by https://www.webslesson.info

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.

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

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', '[email protected]');
Route::post('form-validation/insert', '[email protected]')->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.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

PHP with Laravel for beginners - Become a Master in Laravel

Projects in Laravel: Learn Laravel Building 10 Projects

Laravel for RESTful: Build Your RESTful API with Laravel

Fullstack Web Development With Laravel and Vue.js

Laravel 5.8 Tutorial for Beginners

Laravel 5.8 Ajax CRUD tutorial using Datatable JS

Laravel 5.8 Tutorial from Scratch for Beginners

Build RESTful API In Laravel 5.8 Example

Login with Google in Laravel 5.8 App using Socialite Package

Upgrading Laravel To 6.0 From 5.8

Laravel 6 Release New Features and Upgrade

laravel php javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

PHP Website Development

Skenix Infotech is a leading PHP Web Development Company that helps companies get results with industry best practices. Get affordable PHP Development Services.

Laravel Development Company

Skenix Infotech is a top Laravel Website Development Company with Expert Laravel Developers that provides robust Laravel Development Services at fair costs.

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers? **[Hire Dedicated PHP Developer](https://hourlydeveloper.io/hire-dedicated-php-developer/ "Hire Dedicated PHP Developer")**, who can convert your idea to reality, within the stipulated...

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website? **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")** has always been an industry leader for companies and business owners looking to hire...