You can achieve form validation in Laravel 9 using built in methods. It will validate the form inputs through different types. There are different types of validations methods available. These methods will be used to check types like string, number, email, phone, etc. You can set the validation rule according to the form inputs. If the validation fails, it returns the error message. You can customize the default error messages as well. In this post, I will show the form validation in Laravel 9 form.
Prerequisites
You can create a new project in Laravel 9. It will require the following tools to have in your system.
- PHP >=8.0.2
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
I am assuming, you have already a new project setup. Therefore, I am moving to the form part quickly.
How to Create a CRUD Application in Laravel 9 From Scratch
Create a View For Form Validation in Laravel 9
At the initial step, you have to create a view. I have created a blade file with the name registration.blade.php. This will contain a form with some basic inputs. You can add the below snippet directly or create a form according to your requirement.
<!doctype html>
<html lang="en">
<head>
<title>Laravel 9 Form Validation Tutorial</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-3">
<div class="row my-2">
<div class="col-xl-12">
<h3 class="text-center"> Laravel 9 Form Validation </h3>
</div>
</div>
<form action="{{ route('form') }}" method="POST" autocomplete="off" class="needs-validation">
@csrf
<div class="row">
<div class="col-xl-6 m-auto">
<div class="form-floating mb-3">
<input type="text" name="name" class="form-control @error('name') is-invalid @enderror" id="floatingInput" placeholder="Name">
<label for="floatingInput">Name</label>
@error('name')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating mb-3">
<input type="text" name="email" class="form-control @error('email') is-invalid @enderror" id="floatingInput" placeholder="Email address">
<label for="floatingInput">Email address</label>
@error('email')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating mb-3">
<input type="text" name="phone" class="form-control @error('phone') is-invalid @enderror" id="floatingInput" placeholder="Mobile number">
<label for="floatingInput">Mobile number</label>
@error('phone')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating mb-3">
<input type="password" name="password" class="form-control @error('password') is-invalid @enderror" id="floatingPassword" placeholder="Password">
<label for="floatingPassword">Password</label>
@error('password')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating mb-3">
<input type="password" name="confirmPassword" class="form-control @error('confirmPassword') is-invalid @enderror" id="floatingConfirmPassword" placeholder="Confirm Password">
<label for="floatingConfirmPassword">Confirm Password</label>
@error('confirmPassword')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating mb-3">
<select class="form-select form-control @error('gender') is-invalid @enderror" name="gender" id="floatingSelect" aria-label="Floating label select example">
<option selected value="" >Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="transgender">Transgender</option>
</select>
<label for="floatingSelect">Select</label>
@error('gender')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="form-floating mb-3">
<textarea class="form-control @error('address') is-invalid @enderror" name="address" id="floatingAddress" placeholder="Address"></textarea>
<label for="floatingAddress">Address</label>
@error('address')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
<div class="mb-2">
<button type="submit" class="btn btn-primary btn-lg"> Submit </button>
</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>
How to Create a Dependent Dropdown in Laravel 8 Using Ajax
Create a Controller For Form Validation
For writing the Laravel Form Validation rules, you will need a controller. Hence, create a controller with any name.
php artisan make:controller FormController
After creating the controller, let’s put the below snippet.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FormController extends Controller
{
/**
* Show registration form
* @param NA
* @return View
*/
public function index() {
return view('registration');
}
/**
* Validate form
* @param request
* @return response
*/
public function store(Request $request) {
$request->validate([
'name' => 'required|string|max:20',
'email' => 'required|email|unique:users,email',
'phone' => 'required|numeric|min:10',
'password' => 'required|alpha_num|min:6',
'confirmPassword' => 'required|same:password',
'gender' => 'required',
'address' => 'required|string'
]);
}
}
You can add custom validation message for all the validation rules.
public function store(Request $request)
{
$request->validate(
[
'name' => 'required|string|max:20',
'email' => 'required|email|unique:users,email',
'phone' => 'required|numeric|min:10',
'password' => 'required|alpha_num|min:6',
'confirmPassword' => 'required|same:password',
'gender' => 'required',
'address' => 'required'
],
[
'name.required' => 'Please enter your 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',
'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',
'address.required' => 'Please enter the address',
]
);
}
In the next step, you will have to add the routes. So, in the controller, we have only two functions. Therefore, routes will be added for these functions.
Add Routes in Laravel 9
For adding routes, simply navigate to the web.php file. Now, add the below routes.
Route::get('form', [FormController::class, 'index'])->name('form');
Route::post('form', [FormController::class, 'store'])->name('form');
Laravel 9 Form Validation Result
Check the result to see the custom validation messages.
Conclusion
We have validated a form using Laravel 9 form validator. You can use different validation rules as per the form inputs. These are the basic idea of setting validation rules for the inputs.
Leave a Reply