Form validation is required to prevent unauthentic data submission in the database. It will avoid garbage data collection. Hence, it is always necessary to have validation in the form. The Form validation can be achieved in two ways. You can implement form validation on the client side. However, you can put validation on the server side as well. It is always recommended to put form validation on the server side. So, if somehow, the client-side validation is skipped due to any glitch then the server-side validation will prevent that. Today, we are going to implement Form Validation in Laravel 10. We will be adding the server-side form validation in Laravel 10. Therefore, let’s start quickly.
Prerequisites
In order to apply form validation in Laravel 10, you need a Laravel 10 application. However, for creating a Laravel 10 application, you needed the below tools.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
In this post, we are going to achieve the below result. So, let’s continue with this post.
How to Create a CRUD Application in Laravel 10 For Beginners
Create a Laravel 10 Application For Form Validation
This step is required If you don’t have any existing Laravel 10 applications. If not then, you can create it using the below command.
composer create-project --prefer-dist laravel/laravel myapp
After the project setup, quickly configure a database.
Create and Configure Database For Laravel 10 Application
Firstly, you need to create a database in MySQL if don’t have any. Then secondly, you need to configure the database in the Laravel project.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp_db
DB_USERNAME=root
DB_PASSWORD=root
Once the DB configuration is done, let’s have some work on the Form.
Create a View For Form Validation in Laravel 10
For applying a validation in the Form, you will need to have a view in Laravel. Therefore, create a view and add the below snippets.
<!doctype html>
<html lang="en">
<head>
<title>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 - Form Validation </h3>
<form action="{{ route('employees.store') }}" 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">
<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://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>
If you take a look at the above code snippets, you will see, I have added a form having a couple of inputs.
However, in order to run the above form, you will require a controller and routing.
Laravel 10 Released – Check Out Amazing Features of Laravel 10
Create a Controller in Laravel 10
You can create a controller using the below command. We will be using this controller for handling the form request.
php artisan make:controller EmployeeController
After creating the controller, let’s add the server side validation logic inside it.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class EmployeeController extends Controller
{
/**
* Show the form for creating a new resource.
*/
public function create()
{
return view('create-employee');
}
}
Now, respective to the above function, you will need a route.
Add Routes in Laravel For Form Validation
To render the form, you need to add the below route in the web.php file.
<?php
use App\Http\Controllers\EmployeeController;
use Illuminate\Support\Facades\Route;
Route::get('employees', [EmployeeController::class, 'create'])->name('employees');
Now, you will be able to run the above form. Therefore, run the application, and see the result.
Now, you need to apply the form validation for the above form.
Apply Form Validation in Laravel 10
For validating the form, you can write the validation rules in the same controller by adding a new function. Take a look at the below snippet.
/**
* Store Employee Data
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:20',
'email' => 'required|email|unique:users,email',
'phone' => 'required|digits:10',
'password' => 'required|alpha_num|min:6',
'confirmPassword' => 'required|same:password',
'gender' => 'required|string',
'address' => 'required|string'
]);
dd($request->all());
}
Now, as per the above validation rules, you need to display validation error message in the form as well.
But, before that, you need to add one more route for the submitting the form to this function.
Route::post('employees', [EmployeeController::class, 'store'])->name('employees.store');
After that, we can continue on displaying form validation errors.
Display Validation Error Message in Laravel 10
In Laravel, you can display the validation error messages in two ways.
- Bulk at one place
- Field-level
In first way, you need to iterate all the error message through the loop as shown below.
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
The output of displaying validation error messages using the first way is shown below.
In the second way, you display the error message separately just below the form inputs. This will look more professional and personally, I recommend this.
Therefore, you need to update the blade file as per the below snippet.
<!doctype html>
<html lang="en">
<head>
<title>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 - Form Validation </h3>
<form action="{{ route('employees.store') }}" 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 @error('name') is-invalid @enderror" id="name" placeholder="Name">
<label for="name">Name</label>
@error('name')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating my-3">
<input type="text" name="email" id="email" class="form-control @error('email') is-invalid @enderror" placeholder="Email" />
<label for="email"> Email </label>
@error('email')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating my-3">
<input type="text" name="phone" id="phone" class="form-control @error('phone') is-invalid @enderror" placeholder="Phone Number" />
<label for="phone"> Phone Number </label>
@error('phone')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating my-3">
<input type="password" name="password" id="password" class="form-control @error('password') is-invalid @enderror" placeholder="Password" />
<label for="password"> Password </label>
@error('password')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating my-3">
<input type="password" name="confirmPassword" id="confirmPassword" class="form-control @error('confirmPassword') is-invalid @enderror" placeholder="Confirm Password" />
<label for="confirmPassword">Confirm Password </label>
@error('confirmPassword')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating my-3">
<select class="form-select @error('gender') is-invalid @enderror" 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>
@error('gender')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating my-3">
<input type="text" name="address" id="address" class="form-control @error('address') is-invalid @enderror" placeholder="Address" />
<label for="address">Address </label>
@error('address')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</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://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>
After adding the above snippet, let’s refresh the page to see the updated result.
We displayed the error message separately for each fields. However, we can customize the error messages as well as per our need.
Set Custom Error Message in Laravel Form Validation
By default, Laravel shows up the default error message for the validation rule. However, you can add custom error messages as well by adding in the validation rules array.
/**
* Store Employee Data
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:20',
'email' => 'required|email|unique:users,email',
'phone' => 'required|digits:10',
'password' => 'required|alpha_num|min:6',
'confirmPassword' => 'required|same:password',
'gender' => 'required|string',
'address' => 'required|string'
],
[
'name.required' => 'Please enter your name',
'name.string' => 'Please enter a valid name',
'name.max' => 'Name must not be more than 20 chars',
'email.required' => 'Please enter your email',
'email.email' => 'Email must be a valid email address',
'email.unique' => 'This email is already taken',
'phone.required' => 'Please enter the phone number',
'phone.numeric' => 'Phone number must be a number',
'password.required' => 'Please enter the password',
'password.alpha_num' => 'Password must be alpha numeric chars',
'password.min' => 'Password should be minium 6 chars',
'confirmPassword.required' => 'Please re-enter the password',
'confirmPassword.same' => 'Password must be same',
'gender.required' => 'Please select the gender',
'gender.string' => 'Please select the gender',
'address.required' => 'Please enter the address',
]);
}
Now, check the result of the custom error message.
The validation is done here. But, still, there is one major issue of value resetting in the form.
If you fill up all the details correctly and submit the form then the previous value won’t be pre-filled.
Re-Populate Form Data After Triggering Form Validation
In order to hold back the previous data into the form inputs, you have to add one attribute in the form inputs.
{{ old('inputName') }}
So, after adding for the name field as per the current form, it will look like this.
<input type="text" name="name" class="form-control @error('name') is-invalid @enderror" id="name" placeholder="Name" value="{{ old('name') }}">
Similarly, you can add this in the rest of the inputs, including select, textarea, radio, etc.
That’s it for this post.
Leave a Reply