Form validation is a measured challenge to store validated data. You cannot store incomplete data in the database. This is possible only by proper validation. There are different kinds of validation. Even, you can handle the form validation at the client end and at the server end. The client-side form validation prevents the user from hitting the request to the server. The server-side form validation will allow users to input the data. It will check before inserting it into the database. It may take time to return the validation error response back to the user. I have already shared the post on Laravel 8 Form Validation on the server-side. In this post, I will validate the form at the client-side using the jQuery form validation in Laravel.
Prerequisites
Before creating this Laravel 8 application, you will require to have the below configuration in your system.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
I am going to create a new project here. Let’s create it using the composer.
Create a New Project in Laravel 8
For creating the new project, I will be using the composer. You can use the Laravel installer as well.
composer create-project --prefer-dist laravel/laravel form-validation
Here, the project has been created. Now, I will setup the database for it.
For the database, I will be using MySQL. So, I am creating a new database first.
Create and Configure Database
Open the MySQL command line and hit the below command to create a new database.
CREATE DATABASE form_validation;
After creating the database, we will have to configure it for the Laravel application. So, move to the project root directory and find the .env file there. Now, add the below database details.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=form_validation
DB_USERNAME=root
DB_PASSWORD=root
Don’t forget to replace your database credentials from the above data. Here, our application is connected with the database. Now, in the next step, we will be creating a model and migration. Actually, in this project, we will be validating the form using the jQuery form validation. After the successful validation, the data will be inserted into the database.
Hence, we will require a view, a controller and the model to synchronize with the database. So, let’s do these all step by step.
Create a Model and Migration
In Laravel, we are having a default model and migration for the User module. We can use the same model and migration or you can create a new one. In this project, I am going to use the existing model and migration.
In the migration, I will add some fields for which, I will set the jQuery form validation. So, add the below fields in the user migration file.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('email')->unique();
$table->string('phone')->nullable();
$table->string('password')->nullable();
$table->string('gender')->nullable();
$table->string('dob')->nullable();
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('state')->nullable();
$table->string('zipcode')->nullable();
$table->timestamps();
});
}
Now, as per the above fields, we will set the fillable data in the User Model.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'phone',
'password',
'gender',
'dob',
'address',
'city',
'state',
'zipcode'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
];
}
At last, you have to migrate the table for creating the schema in the database.
php artisan migrate
Here, the tables are migrated in the database.
In the next step, we will have to create a controller for the User. So, let’s create it.
Create a Controller in Laravel 8
We will create a controller to extract form inputs from the view. The below command will create a controller with the name UserController.
php artisan make:controller UserController
After creating the controller, let’s add some code there.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index() {
return view("register");
}
// register user
public function registerUser(Request $request) {
$userArray = array(
"first_name" => $request->firstName,
"last_name" => $request->lastName,
"email" => $request->email,
"phone" => $request->phone,
"password" => $request->password,
"gender" => $request->gender,
"dob" => $request->dateOfBirth,
"address" => $request->address,
"city" => $request->city,
"state" => $request->state,
"zipcode" => $request->zipcode,
);
$user = User::create($userArray);
if(!is_null($user)) {
return back()->with("success", "Registration completed successfully");
}
else {
return back()->with("failed", "Registration failed. Try again.");
}
}
}
As per the controller, we will have to create a view. In that view, I will implement the jQuery form validation.
Create a View for Form Validation
We will require a view for creating a basic registration form. In this form, I will try to put the general fields which are using for any kind of form. Then, on that form inputs, I will create the validation rules.
For the validation, I will be using the jQuery validator that will require the jQuery. You can use the CDN for both (jQuery and Validator).
So, here, I will create a view with the name register.blade.php. After creating the blade file, just add the below snippet. Here, I have added the basic registration form. Also, I have added the jQuery CDN.
<!doctype html>
<html lang="en">
<head>
<title>User Registration | Form Validation Using jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container pt-3">
<form action="{{url('register-user')}}" method="POST" autocomplete="off" id="regForm">
@csrf
<div class="row">
<div class="col-xl-8 m-auto">
<div class="card shadow">
<div class="card-header">
<h4 class="text-center font-weight-bold"> Form Validation Using jQuery Validator </h4>
</div>
<div class="card-body pl-4 pr-4">
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="firstName"> First Name <span class="text-danger">*</span> </label>
<input type="text" name="firstName" id="firstName" class="form-control" placeholder="First Name">
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="lastName"> Last Name <span class="text-danger">*</span> </label>
<input type="text" name="lastName" id="lastName" class="form-control" placeholder="Last Name">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="email"> Email <span class="text-danger">*</span> </label>
<input type="email" name="email" id="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="phone"> Phone <span class="text-danger">*</span> </label>
<input type="text" name="phone" id="phone" class="form-control" placeholder="Phone">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="password"> Password <span class="text-danger">*</span> </label>
<input type="password" name="password" id="password" class="form-control" placeholder="Password">
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="confirmPassword"> Confirm Password <span class="text-danger">*</span> </label>
<input type="password" name="confirmPassword" id="confirmPassword" class="form-control" placeholder="Confirm Password">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="gender"> Gender <span class="text-danger">*</span> </label>
<select class="form-control" name="gender" id="gender">
<option selected value="" disabled>Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="dateOfBirth"> Date of Birth <span class="text-danger">*</span> </label>
<input type="date" name="dateOfBirth" id="dateOfBirth" class="form-control" placeholder="Date of Birth">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="address"> Address <span class="text-danger">*</span></label>
<input type="text" name="address" id="address" class="form-control" placeholder="Address">
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="city"> City <span class="text-danger">*</span></label>
<input type="text" name="city" id="city" class="form-control" placeholder="City">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="state"> State <span class="text-danger">*</span> </label>
<input type="text" name="state" id="state" class="form-control" placeholder="State">
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="zipcode"> Zip Code <span class="text-danger">*</span></label>
<input type="text" name="zipcode" id="zipcode" class="form-control" placeholder="Zip Code">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6 offset-lg-6 text-right">
<button type="submit" class="btn btn-success"> Create your account </button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
After adding the above snippet, we will have to create some routes.
Create Routes
We will have to create the routes in the web.php file. So, add these routes there.
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::get("register", [UserController::class, "index"]);
Route::post("register-user", [UserController::class, "registerUser"]);
So, when you will run the application with the register route. You will get the result as showing below.
Here, we have the form ready and it required the form validation rules. So, let’s add it.
Add the Validation Rules using jQuery Validator
Firstly, we will add the jQuery Form validator CDN. You can download it’s source file too.
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js
We will add the above CDN after the jQuery in our blade file (register.blade.php).
After adding the CDN, we will have to write some validation rules for the specific form. Here, we are validation the inputs inside a form, so, we will write the validation rules for the form by using the selector attribute. In the form attribute, I have already defined the form id and here, I have selected the form using the same id.
Then, I have created a rules of object for the every inputs using their id.
<script>
$(document).ready(function() {
$("#regForm").validate({
rules: {
firstName: "required",
lastName: "required",
email: "required",
phone: "required",
password: "required",
confirmPassword: "required",
gender: "required",
dateOfBirth: "required",
address: "required",
city: "required",
state: "required",
zipcode: "required",
}
});
});
</script>
Add the above code before the closing of the body in the same blade file. Now, refresh the page and submit the form to see the result. Here, you can see, we got the validation error message for the required fields.
Now, I will add a basic CSS for the validation error message. So, that it will look better.
<style>
label.error {
color: #dc3545;
font-size: 14px;
}
</style>
Add the above CSS in the same blade file and refresh the page and try to register the form. You will have the below result.
Here, we got the validation error message. But what if we can modify the validation error message for the required fields? So, let’s do it.
Custom Message For jQuery Form Validation Rules
We can set the custom error messages for every inputs. Here, I have added the custom messages for the required attributes.
<script>
$(document).ready(function() {
$("#regForm").validate({
rules: {
firstName: "required",
lastName: "required",
email: "required",
phone: "required",
password: "required",
confirmPassword: "required",
gender: "required",
dateOfBirth: "required",
address: "required",
city: "required",
state: "required",
zipcode: "required",
},
messages: {
firstName: "First name is required",
lastName: "Last name is required",
email: "Email is required",
phone: "Phone number is required",
password: "Password is required",
confirmPassword: "Confirm password is required",
gender: "Please select the gender",
dateOfBirth: "Date of birth is required",
address: "Address is required",
city: "City is required",
state: "State is required",
zipcode: "Zipcode is required",
}
});
});
</script>
To check the result, refresh and try submitting the form again. Here, you will have the below result with the custom error messages.
This is at a basic level validation. But, what if we want to validate the form in more detail, like we want a valid email address, phone number, password, same password for confirmation and all?
In that case, we have to write the rules separately for each inputs fields by creating it’s object.
Advanced Form Validation Using jQuery Form Validation
Here, we will add the validation rules separately for each inputs fields. So, we will have to add the object of that input and inside that object, we will define the rules. Similarly, for the custom messages, we will have to do the same thing by creating an object and then the set custom messages for the each rules.
<script>
$(document).ready(function() {
$("#regForm").validate({
rules: {
firstName: {
required: true,
maxlength: 20,
},
lastName:{
required: true,
maxlength: 20,
},
email: {
required: true,
email: true,
maxlength: 50
},
phone: {
required: true,
minlength: 10,
maxlength: 10,
number: true
},
password: {
required: true,
minlength: 5
},
confirmPassword: {
required: true,
equalTo: "#password"
},
gender: {
required: true,
},
dateOfBirth: {
required: true,
date: true
},
address: {
required: true,
maxlength: 50
},
city: {
required: true,
maxlength: 40
},
state: {
required: true,
maxlength: 40
},
zipcode: {
required: true,
minlength: 6,
maxlength: 6
}
},
messages: {
firstName: {
required: "First name is required",
maxlength: "First name cannot be more than 20 characters"
},
lastName: {
required: "Last name is required",
maxlength: "Last name cannot be more than 20 characters"
},
email: {
required: "Email is required",
email: "Email must be a valid email address",
maxlength: "Email cannot be more than 50 characters",
},
phone: {
required: "Phone number is required",
minlength: "Phone number must be of 10 digits"
},
password: {
required: "Password is required",
minlength: "Password must be at least 5 characters"
},
confirmPassword: {
required: "Confirm password is required",
equalTo: "Password and confirm password should same"
},
gender: {
required: "Please select the gender",
},
dateOfBirth: {
required: "Date of birth is required",
date: "Date of birth should be a valid date"
},
address: {
required: "Address is required",
maxlength: "Address cannot not be more than 50 characters"
},
city: {
required: "City is required",
maxlength: "City cannot be more than 40 characters"
},
state: {
required: "State is required",
maxlength: "City cannot be more than 40 characters"
},
zipcode: {
required: "Zipcode is required",
minlength: "Zipcode must be of 6 digits",
maxlength: "Zipcode cannot be more than 6 digits"
}
}
});
});
</script>
Now, refresh the form and try submitting it. Here, you will get the error message for every specific rule.
Now, try filling up the correct details and submit the form. For the successful registration, you will get the success response as showing below.
So, this will be the final code of register.blade.php.
<!doctype html>
<html lang="en">
<head>
<title>User Registration | Form Validation Using jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
label.error {
color: #dc3545;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container pt-3">
<form action="{{url('register-user')}}" method="POST" autocomplete="off" id="regForm">
@csrf
<div class="row">
<div class="col-xl-8 m-auto">
<div class="card shadow">
<div class="card-header">
<h4 class="text-center font-weight-bold"> Form Validation Using jQuery Validator </h4>
</div>
<div class="card-body pl-4 pr-4">
@if(Session::has("success"))
<div class="alert alert-success">
{{Session::get("success")}}
</div>
@elseif(Session::has("failed"))
{{Session::get("failed")}}
@endif
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="firstName"> First Name <span class="text-danger">*</span> </label>
<input type="text" name="firstName" id="firstName" class="form-control" placeholder="First Name">
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="lastName"> Last Name <span class="text-danger">*</span> </label>
<input type="text" name="lastName" id="lastName" class="form-control" placeholder="Last Name">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="email"> Email <span class="text-danger">*</span> </label>
<input type="email" name="email" id="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="phone"> Phone <span class="text-danger">*</span> </label>
<input type="text" name="phone" id="phone" class="form-control" placeholder="Phone">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="password"> Password <span class="text-danger">*</span> </label>
<input type="password" name="password" id="password" class="form-control" placeholder="Password">
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="confirmPassword"> Confirm Password <span class="text-danger">*</span> </label>
<input type="password" name="confirmPassword" id="confirmPassword" class="form-control" placeholder="Confirm Password">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="gender"> Gender <span class="text-danger">*</span> </label>
<select class="form-control" name="gender" id="gender">
<option selected value="" disabled>Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="dateOfBirth"> Date of Birth <span class="text-danger">*</span> </label>
<input type="date" name="dateOfBirth" id="dateOfBirth" class="form-control" placeholder="Date of Birth">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="address"> Address <span class="text-danger">*</span></label>
<input type="text" name="address" id="address" class="form-control" placeholder="Address">
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="city"> City <span class="text-danger">*</span></label>
<input type="text" name="city" id="city" class="form-control" placeholder="City">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6">
<div class="form-group">
<label for="state"> State <span class="text-danger">*</span> </label>
<input type="text" name="state" id="state" class="form-control" placeholder="State">
</div>
</div>
<div class="col-xl-6">
<div class="form-group">
<label for="zipcode"> Zip Code <span class="text-danger">*</span></label>
<input type="text" name="zipcode" id="zipcode" class="form-control" placeholder="Zip Code">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6 offset-lg-6 text-right">
<button type="submit" class="btn btn-success"> Create your account </button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
<script>
$(document).ready(function() {
$("#regForm").validate({
rules: {
firstName: {
required: true,
maxlength: 20,
},
lastName:{
required: true,
maxlength: 20,
},
email: {
required: true,
email: true,
maxlength: 50
},
phone: {
required: true,
minlength: 10,
maxlength: 10,
number: true
},
password: {
required: true,
minlength: 5
},
confirmPassword: {
required: true,
equalTo: "#password"
},
gender: {
required: true,
},
dateOfBirth: {
required: true,
date: true
},
address: {
required: true,
maxlength: 50
},
city: {
required: true,
maxlength: 40
},
state: {
required: true,
maxlength: 40
},
zipcode: {
required: true,
minlength: 6,
maxlength: 6
}
},
messages: {
firstName: {
required: "First name is required",
maxlength: "First name cannot be more than 20 characters"
},
lastName: {
required: "Last name is required",
maxlength: "Last name cannot be more than 20 characters"
},
email: {
required: "Email is required",
email: "Email must be a valid email address",
maxlength: "Email cannot be more than 50 characters",
},
phone: {
required: "Phone number is required",
minlength: "Phone number must be of 10 digits"
},
password: {
required: "Password is required",
minlength: "Password must be at least 5 characters"
},
confirmPassword: {
required: "Confirm password is required",
equalTo: "Password and confirm password should same"
},
gender: {
required: "Please select the gender",
},
dateOfBirth: {
required: "Date of birth is required",
date: "Date of birth should be a valid date"
},
address: {
required: "Address is required",
maxlength: "Address cannot not be more than 50 characters"
},
city: {
required: "City is required",
maxlength: "City cannot be more than 40 characters"
},
state: {
required: "State is required",
maxlength: "City cannot be more than 40 characters"
},
zipcode: {
required: "Zipcode is required",
minlength: "Zipcode must be of 6 digits",
maxlength: "Zipcode cannot be more than 6 digits"
}
}
});
});
</script>
</body>
</html>
Conclusion
We have added the form validation on the client-side in Laravel 8. The jQuery provides the validator js to validate the form. We have to write the validation rules as per our requirements. Also, we can set the custom message for the validation error. We can define the validation attribute like required, email, number, maxlength, minlength, etc. So, this was the basic implementation for the form validation. You can use it at a more advanced level. So, I hope, you will find it helpful somewhere. Thank you.
Leave a Reply