How to validate mobile phone numbers in Laravel
In this tutorial, we will learn How to validate mobile phone numbers in Laravel. we most of the requirements to add phone number validation in our Laravel project. Mobile validation is a very important thing from a security point of view for a web application. In this example of Laravel mobile number validation. we will detail 10 digit mobile number validation in Laravel. you will learn phone number validation in Laravel.
I will show how to add mobile validation in Laravel using regex. and we can easily use your controller method. I will give you two ways to add phone number validation in Laravel. and show you controller code and preview here.
Example 1:
We will write phone number validation in UsersController where we will process the user’s table data.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Validator;
class UsersController extends Controller
{
public function create()
{
return view('users.create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'phone' => 'required|digits:10',
'email' => 'required|email|unique:users'
]);
$input = $request->all();
$user = User::create($input);
return back()->with('success', 'User created successful!');
}
}
Example 2:
In the second example, we will use regex for the user’s mobile phone number validation before storing user data in our database. we will write the validation in UsersController like the below code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Validator;
class UsersController extends Controller
{
public function create()
{
return view('createUser');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
'email' => 'required|email|unique:users'
]);
$input = $request->all();
$user = User::create($input);
return back()->with('success', 'User created successful!');
}
}