Client-side form validation is a technique used to validate user input on the client side. Here client-side refers to the user’s browser. This means before submitting the form data to the server, the data will be validated. This approach helps to provide instant feedback to the user. Also, the main benefit of using client side validation in Laravel is to reduce the number of server requests and server-side validation errors. There are several benefits to using client side form validation. First and foremost, it improves the user experience by providing instant feedback to the user if they enter invalid data. This helps users to correct their mistakes quickly and ensures that the form is filled out correctly before it is submitted. In this post, we will be implementing client side validation in Laravel 10 form using Parsley JS.
We are going to achieve the below result of the client side validation in Laravel 10 form.
You can set different sets of validation rules as provided by Parsley.js.
But, before moving to the example, let’s take a look at the Parsley.js library.
What is Parsley JS
Parsley.js is a powerful and flexible JavaScript library that is used for form validation in web applications. It provides a user-friendly and customizable interface for validating form inputs on the client side. This is used in web applications. Parsley.js is written in JavaScript and is built on top of the jQuery library.
This provides a wide range of pre-built validation rules. You can use these to validate various types of input data, such as required fields, email addresses, phone numbers, URLs, dates, and more. These rules can be easily applied to form inputs using HTML5 data attributes or JavaScript code.
Prerequisites
In this post, we are going to implement client side validation in Laravel 10 form. Hence, you need a Laravel 10 project setup. However, for using Parseley.js, it is not recommended to use only Laravel 10. You can use the older version of Laravel as well.
In order to work with the Laravel 10 application, you will require the below configurations.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
For creating the Laravel 10 application, we will be using compost. However, you can use the Laravel installer as well.
Create a Project For Client Side Form Validation in Laravel 10
At the very first step, navigate to the terminal and hit the below command.
composer create-project --prefer-dist laravel/laravel form-validation
The command will take a couple of seconds to have a latest version of Laravel (Laravel 10) application.
After creating the project, open it in the editor, and let’s configure a database.
Configure Database For Laravel 10 Project
For the database configuration, you need a database first. Hence, create a database and then navigate to the project folder. There you will find .env file. Therefore, under the Database section, you need to add the DB credentials.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE={{ DB_NAME }}
DB_USERNAME={{ DB_USER }}
DB_PASSWORD={{ DB_PASSWORD }}
Now, the application is connected to the database. Hence, in the next step, we will create a Controller for rendering the form.
In this post, I am not going to perform any DB operations. Hence, I won’t create any model and migration. Directly, I will create a form and then will apply the client side validation using Parsley.js library.
Create a Controller in Laravel 10
For creating a controller, simply hit the below command in the terminal.
php artisan make:controller FormController
After creating a controller, let’s put the below snippet.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FormController extends Controller
{
/**
* Function : Load View
*/
public function index() {
return view('register-form');
}
/**
* Function : Store
* @param request
*/
public function store(Request $request) {
return $request->all();
}
}
Now, as per the above blade, you need to create routes.
Create Web Routes For Form Validation
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FormController;
Route::get('register', [FormController::class, 'index'])->name('register');
Route::post('register', [FormController::class, 'store'])->name('register.store');
After adding the routes, you can move to the next step in which we will be creating a form.
Create a View For a Form Handling in Laravel 10
You need to create a view in which there will be a form having a couple of inputs. On this form, we will apply client side form validation using Parsley.js.
Therefore, create a view named register-form.blade.php and add the below snippet.
<!doctype html>
<html lang="en">
<head>
<title>Client Side Form Validation in Laravel 10</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container py-5">
<h3 class="text-center fw-bold">Laravel 10 - Client Side Form Validation </h3>
<form action="{{ route('register.store') }}" id="register-form" method="post" class="needs-validation" autocomplete="off">
@csrf
<div class="row mt-4">
<div class="col-xl-6 col-lg-6 mx-auto">
<div class="card shadow">
<div class="card-body">
<div class="form-floating mb-3">
<input type="text" name="name" class="form-control" id="name" placeholder="Name" value="{{ old('name') }}">
<label for="name">Name</label>
</div>
<div class="form-floating my-3">
<input type="text" name="email" id="email" class="form-control" placeholder="Email" />
<label for="email"> Email </label>
</div>
<div class="form-floating my-3">
<input type="text" name="phone" id="phone" class="form-control" placeholder="Phone Number" />
<label for="phone"> Phone Number </label>
</div>
<div class="form-floating my-3">
<input type="password" name="password" id="password" class="form-control" placeholder="Password" />
<label for="password"> Password </label>
</div>
<div class="form-floating my-3">
<input type="password" name="confirmPassword" id="confirmPassword" class="form-control" placeholder="Confirm Password" />
<label for="confirmPassword">Confirm Password </label>
</div>
<div class="form-floating my-3">
<select class="form-select" name="gender" id="gender">
<option value="">Select Gender </option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label for="gender"> Gender </label>
</div>
<div class="form-floating my-3">
<input type="text" name="address" id="address" class="form-control" placeholder="Address" />
<label for="address">Address </label>
</div>
</div>
<div class="card-footer">
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg"> Save </button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"
integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"
integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous">
</script>
</body>
</html>
Now, if you run the application in the browser then you will have the below result of the form.
Now, we have to apply client side validation in the above form.
Apply Client Side Validation in Laravel 10 Using Parsley.js
You can use Parsley.js by installing it through npm or else you can use its minified js.
I will be using its minified version. Hence, for that, I will just copy the Parsley.js minified version and paste it into a new JS file that I have created in the public/assets/js folder.
The folder architecture will be as shown below.
app
|
|
public
|____ assets
| |_____ js
| | |____ parsley.js
| | |
| | |
After creating the file, simply paste the minified version of Parsley.js.
Now, at the very first step of the applying validation, you need to import the created file in the register-form.blade.php
<script src="{{ asset('assets/js/parsley.js') }} type="text/javascript"></script>
After that, you need to initialize the parsley.js library for the form in order to invoke validation. So, you have to pass the form selector as shown below.
<script>
$('form-selector
').parsley();
</script>
Now, you can use parsley js validation attribute with inputs. So, at the very first, I will put the required attribute validation using the parsley validator for the inputs.
data-parsley-required
After adding the above attribute with the form inputs, the snippet will become like this.
<!doctype html>
<html lang="en">
<head>
<title>Client Side Form Validation in Laravel 10</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container py-5">
<h3 class="text-center fw-bold">Laravel 10 - Client Side Form Validation </h3>
<form action="{{ route('register.store') }}" id="register-form" method="post" class="needs-validation" autocomplete="off">
@csrf
<div class="row mt-4">
<div class="col-xl-6 col-lg-6 mx-auto">
<div class="card shadow">
<div class="card-body">
<div class="form-floating mb-3">
<input type="text" name="name" data-parsley-required class="form-control" id="name" placeholder="Name" value="{{ old('name') }}">
<label for="name">Name</label>
</div>
<div class="form-floating my-3">
<input type="text" name="email" data-parsley-required id="email" class="form-control" placeholder="Email" />
<label for="email"> Email </label>
</div>
<div class="form-floating my-3">
<input type="text" name="phone" data-parsley-required id="phone" class="form-control" placeholder="Phone Number" />
<label for="phone"> Phone Number </label>
</div>
<div class="form-floating my-3">
<input type="password" name="password" data-parsley-required id="password" class="form-control" placeholder="Password" />
<label for="password"> Password </label>
</div>
<div class="form-floating my-3">
<input type="password" name="confirmPassword" data-parsley-required id="confirmPassword" class="form-control" placeholder="Confirm Password" />
<label for="confirmPassword">Confirm Password </label>
</div>
<div class="form-floating my-3">
<select class="form-select" data-parsley-required="" name="gender" id="gender">
<option value="">Select Gender </option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label for="gender"> Gender </label>
</div>
<div class="form-floating my-3">
<input type="text" name="address" data-parsley-required id="address" class="form-control" placeholder="Address" />
<label for="address">Address </label>
</div>
</div>
<div class="card-footer">
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg"> Save </button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"
integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"
integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous">
</script>
<script src="{{asset('assets/js/parsley.js')}}" type="text/javascript"> </script>
<script>
$('#register-form').parsley();
</script>
</body>
</html>
If you refresh the form and check the result then it will look like shown below.
Yes, we got something in the terms of validation errors. But, it doesn’t look good. So, let’s beautify this little bit using CSS.
<style>
.parsley-errors-list {
padding: 0px!important;
}
.parsley-errors-list li {
list-style: none;
color: #cc0000;
}
</style>
Now, after adding this CSS, let’s refresh the page to see the result now.
It is looking a little bit good now. However, you can set the custom error message instead of the default one.
Set Custom Validation Error Message in Parsley.js
For writing a custom error message in parsley.js, you need to set one attribute in every input.
data-parsley-required-message="Some Custom Message"
Now, let’s apply this attribute to all inputs.
So, after updating the input attribute the code will look like this.
<!doctype html>
<html lang="en">
<head>
<title>Client Side Form Validation in Laravel 10</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<style>
.parsley-errors-list {
padding: 0px!important;
}
.parsley-errors-list li {
list-style: none;
color: #cc0000;
}
</style>
</head>
<body>
<div class="container py-5">
<h3 class="text-center fw-bold">Laravel 10 - Client Side Form Validation </h3>
<form action="{{ route('register.store') }}" id="register-form" method="post" class="needs-validation" autocomplete="off">
@csrf
<div class="row mt-4">
<div class="col-xl-6 col-lg-6 mx-auto">
<div class="card shadow">
<div class="card-body">
<div class="form-floating mb-3">
<input type="text" name="name" data-parsley-required data-parsley-required-message="Please enter your name" class="form-control" id="name" placeholder="Name" value="{{ old('name') }}">
<label for="name">Name</label>
</div>
<div class="form-floating my-3">
<input type="text" name="email" data-parsley-required id="email" data-parsley-required-message="Please enter your email" class="form-control" placeholder="Email" />
<label for="email"> Email </label>
</div>
<div class="form-floating my-3">
<input type="text" name="phone" data-parsley-required id="phone" data-parsley-required-message="Please enter your phone number" class="form-control" placeholder="Phone Number" />
<label for="phone"> Phone Number </label>
</div>
<div class="form-floating my-3">
<input type="password" name="password" data-parsley-required data-parsley-required-message="Please enter your password" id="password" class="form-control" placeholder="Password" />
<label for="password"> Password </label>
</div>
<div class="form-floating my-3">
<input type="password" name="confirmPassword" data-parsley-required data-parsley-required-message="Please re-enter your password" id="confirmPassword" class="form-control" placeholder="Confirm Password" />
<label for="confirmPassword">Confirm Password </label>
</div>
<div class="form-floating my-3">
<select class="form-select" data-parsley-required data-parsley-required-message="Please select your gender" name="gender" id="gender">
<option value="">Select Gender </option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label for="gender"> Gender </label>
</div>
<div class="form-floating my-3">
<input type="text" name="address" data-parsley-required data-parsley-required-message="Please enter your address" id="address" class="form-control" placeholder="Address" />
<label for="address">Address </label>
</div>
</div>
<div class="card-footer">
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg"> Save </button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"
integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"
integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous">
</script>
<script src="{{asset('assets/js/parsley.js')}}" type="text/javascript"> </script>
<script>
$('#register-form').parsley();
</script>
</body>
</html>
Now, just refresh the page and see the updated result.
However, the validation is not completed yet. This means you can apply more sets of validation rules.
<!doctype html>
<html lang="en">
<head>
<title>Client Side Form Validation in Laravel 10</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<style>
.parsley-errors-list {
padding: 0px !important;
}
.parsley-errors-list li {
list-style: none;
color: #cc0000;
}
</style>
</head>
<body>
<div class="container py-5">
<h3 class="text-center fw-bold">Laravel 10 - Client Side Form Validation </h3>
<form action="{{ route('register.store') }}" id="register-form" method="post" class="needs-validation"
autocomplete="off">
@csrf
<div class="row mt-4">
<div class="col-xl-6 col-lg-6 mx-auto">
<div class="card shadow">
<div class="card-body">
<div class="form-floating mb-3">
<input type="text" name="name" id="name"
data-parsley-required
data-parsley-required-message="Please enter your name"
data-parsley-minlength="3"
data-parsley-minlength-message="Name is too short"
data-parsley-maxlength="100"
data-parsley-maxlength-message="Name is too long"
class="form-control"
placeholder="Name" />
<label for="name">Name</label>
</div>
<div class="form-floating my-3">
<input type="text" name="email" id="email"
data-parsley-required
data-parsley-required-message="Please enter your email"
data-parsley-type="email"
data-parsley-type-message="Email must be a valid email address"
class="form-control"
placeholder="Email" />
<label for="email"> Email </label>
</div>
<div class="form-floating my-3">
<input type="text" name="phone" id="phone"
data-parsley-required
data-parsley-required-message="Please enter your phone number"
data-parsley-type="digits"
data-parsley-type-message="Phone number must be a number"
data-parsley-minlength="10"
data-parsley-minlength-message="Phone number must be minimum 10 digits"
data-parsley-maxlength="10"
data-parsley-maxlength-message="Phone number must be max 10 digits"
class="form-control"
placeholder="Phone Number" />
<label for="phone"> Phone Number </label>
</div>
<div class="form-floating my-3">
<input type="password" name="password" id="password"
data-parsley-required
data-parsley-required-message="Please enter your password"
data-parsley-type="alphanum"
data-parsley-type-message="Password must be alphanumeric"
data-parsley-minlength="6"
data-parsley-minlength-message="Password must be atleast 6 chars long"
data-parsley-maxlength="10"
data-parsley-maxlength-message="Password must be max 10 chars long"
class="form-control" placeholder="Password" />
<label for="password"> Password </label>
</div>
<div class="form-floating my-3">
<input type="password" name="confirmPassword" id="confirmPassword"
data-parsley-required
data-parsley-required-message="Please re-enter your password"
data-parsley-equalto="#password"
data-parsley-equalto-message="Confirm Password must be same as Password"
class="form-control"
placeholder="Confirm Password" />
<label for="confirmPassword">Confirm Password </label>
</div>
<div class="form-floating my-3">
<select class="form-select" name="gender" id="gender"
data-parsley-required
data-parsley-required-message="Please select your gender">
<option value="">Select Gender </option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label for="gender"> Gender </label>
</div>
<div class="form-floating my-3">
<input type="text" name="address" id="address"
data-parsley-required
data-parsley-required-message="Please enter your address"
data-parsley-minlength="10"
data-parsley-minlength-message="Address is too short"
data-parsley-maxlength="100"
data-parsley-maxlength-message="Address is too long"
class="form-control" placeholder="Address" />
<label for="address">Address </label>
</div>
</div>
<div class="card-footer">
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg"> Save </button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"
integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"
integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"
integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous">
</script>
<script src="{{ asset('assets/js/parsley.js') }}" type="text/javascript"></script>
<script>
$('#register-form').parsley();
</script>
</body>
</html>
After adding some more validation rules, the blade file will be updated as shown above. Now, you can run the application to see the result.
Parsely.js Validation Attributes
Parsley.js provides multiple attributes for validating different types of rules. For example, type number, email, etc. Even the most important thing is you can write REGEX directly in order to validate with any specific pattern.
Take a look at the below table.
Name | API Usage | Description |
---|---|---|
Required | data-parsley-required | Validates that a required field has been filled with a non blank value. If data-parsley-required="false", validator is deactivated and the field is not required. |
data-parsley-type="email" | Validates that a value is a valid email address. | |
Number | data-parsley-type="number" | Validates that a value is a valid number according to the given step, min and original value. |
Integer | data-parsley-type="integer" | Validates that a value is a valid integer. |
Digits | data-parsley-type="digits" | Validates that a value is only digits. |
Alphanum | data-parsley-type="alphanum" | Validates that a value is a valid alphanumeric string. |
URL | data-parsley-type="url" | Validates that a value is a valid url. |
Minlength | data-parsley-minlength="6" | Validates that the length of a string is at least as long as the given limit. |
Maxlength | data-parsley-maxlength="10" | Validates that the length of a string is not longer than the given limit. |
Min | data-parsley-min="6" | Validates that a given input (number or date) or date is greater than or equal to some minimum (number or date.) |
Max | data-parsley-max="10" | Validates that the given input (number or date) is less than or equal to some maximum value (number or date). |
Range | data-parsley-range="[6, 10]" | Validates that a given value (number or date) is between some minimum and maximum values (numbers or dates). |
Pattern | data-parsley-pattern="\d+" | Validates that a value matches a specific regular expression (regex). |
MinCheck | data-parsley-mincheck="3" | Validates that a certain minimum number of checkboxes in a group are checked. |
Equalto | data-parsley-equalto="#anotherfield" | Validates that the value is identical to another field's value (useful for password confirmation check). |
Check | data-parsley-check="[1, 3]" | Validates that the number of checked checkboxes in a group is within a certain range. |
MaxCheck | data-parsley-maxcheck="3" | Validates that a certain maximum number of checkboxes in a group are checked. |
For more information, you can visit the official site of Parsley.js.
That’s it for this post, I hope this will help you in implementing client side form validation.
Leave a Reply