In this guide, we will share with you how to validate phone number in laravel.
We will be discussing how you can validate phone numbers using digits of validator
library.
This tutorial is valid and works from any laravel version including laravel 10, 9, 8, 7 and 6 as well.
Let’s get started!
Table of Contents
Validate Phone Number Using Validator
We will using validator
which is laravel built-in class in order to validate the request.
We will using the validator
digit
function in order to count number of digits, here is how you do in the controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class HomeController extends Controller
{
//
public function index(Request $request){
$validator = Validator::make([
'phone_number' => 'required|numeric|digits:10',
]);
if ($validator->fails()) {
// if validation fails run this
} else {
// if validation pass run this
}
}
}
In the above code, on the request variable phone_number
, we are applying the Validator
rules. Validator
rules are set here is that it is required so we added required
, then the number should be a number that’s way we are adding numeric
and then the number should have 10 digits that’s why are adding digits:10
.
Conclusion
Hope in the above article, you have learned how to validate phone number request in laravel.
Let me know if you have any questions, I will see you in the next one.
Write a Reply or Comment