When you create any Laravel application, it’s important to validate user input. In this tutorial, let’s learn about the various methods of validating phone or mobile numbers in Laravel.
1. Laravel Controller
Controllers can help you group related request-handling logic into a single class. For example, a PhoneController class can handle all incoming requests related to a mobile number, including showing, creating, validating, updating, and deleting numbers. This helps perform form validation in a Laravel application. For example when a new user will try to register their details including contact information.
The controller class saves you from defining all of the request-handling logic in the routes.php file. This results in a more organized and structured code base that is easier to maintain. By default, these Controllers are stored in the app/Http/Controllers directory.
A controller class successfully validates phone numbers. But we need to define the format of the numbers we are using. Here we need to handle both landline and mobile phone numbers for different countries, as per the country codes. The numbers are 10 digits in length and might be more as per the extensions used.
Step 1: Set up a Route
We need to create a route to start working with the Controller class. Controllers save us from handling validation logic in the route files. However, we must always add a route to our Controller class in routes/web.php with the command below.
use App\Http\Controllers\MobileController;
Route::post('/post', [MobileController::class, save]);
Step 2: Create the Mobile Number Controller Class
The MobileController class acts as a validator extension to the base Controller class. Let’s check the code for the Controller class.
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class MobileController extends Controller
{
public function save(Request $request)
{
$validated = $request->validate([
'mobile_number' => 'required|numeric|digits:10'
]);
//If the number passes, the method will continue from here.
}
}
The code above shows how to save a user’s information, including their mobile numbers post validation. The validate function takes in a mobile number and checks if it obeys the required criteria for a mobile number. For example, a numeric entry, and 10 digits for the entry.
When a number is validated using the method above, it gives two different results:
- On validation pass, the code executes normally.
- On validation fail, an Illuminate\Validation\ValidationException exception will be thrown. The user will automatically get back a proper error response.
On validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. A JSON response with the validation error messages is returned for XHR requests.
Laravel Controller Class validation works from Laravel 5.1 onwards. This method is not supported by Laravel 5.0. It uses the Validator class for mobile phone validation.
Rules breakdown for Mobile Number validation
We provided the following validation rules: ‘required|numeric|min:10’. But what do each of these mean? Here are the definitions for each:
Let’s check out the definition of validation rules used. So for the rule, ‘required|numeric|min:10’:
- Numeric: The input entry must be numeric, i.e. a number.
- min:10: Denotes the input field must be at least 10 characters in length.
- required: The input field must be present and should not be empty.
A field is considered “empty” for the following conditions:
- Null values.
- Empty string values.
- Empty array or empty countable object values.
- A value is an uploaded file and has no path.
If the user inputs a numeric value it should be 10 characters in length. Our MobileController class will ensure the user’s mobile number is properly validated.
However, we can also use the Regex pattern within the Laravel framework and not create a controller class. Let’s learn in the next section, the use of regex patterns for mobile number validation in Laravel.
2. Regex Expressions
Using Regex to validate phone numbers, won’t require using the digits or numeric rules as shown previously. Note that by using Regex, you can find numerous patterns that can suit your use case. Let’s make a simple save function that is designed to store telephone numbers. It uses a regular expression that acts as our own validation rule.
Check out the following code for a validation example using Regex expression for phone validation.
public function save(Request $request){
$validated = $request->validate($request,[
'mobile_number' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10'
]);
//method continues here.
}
Validation rules for our mobile_number input:
- required: the rule validates for null, empty strings and arrays, or uploaded files with no paths.
- regex:/^([0-9\s\-\+\(\)]*)$/: the regex pattern accepts numbers between 0-9, and additional characters as ‘-‘,’+’,'(‘, and ‘)’. Input that won’t match the regex pattern will be rejected.
- min:10: The input must have at least 10 characters in length. Inputs that don’t follow this size validation rule will be rejected.
Regex patterns can be used in this way for US number validation. Different countries have varying codes. The regex pattern varies for them accordingly.
The Regex pattern for UK mobile number validation is as follows:
^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$
3. Validation using a library
An alternative mobile number validation method is using the phone validator package.
This is a C++, Java, and JavaScript library for parsing, formatting, and validating international phone numbers. It handles all regions and countries of the world and has useful functionality. To add mobile validation, an optimized Java version of the library runs on smartphones. It is used by the Android framework to validate a mobile number.
4. Validation using an API
Another alternative way is to have an API that acts as a phone number validator. There are many amazing APIs, like this phone number validation API, that have many functionalities. These are often easier to integrate into our existing workflows. This Abstract API can also detect fake and invalid numbers from non-existent service providers. This is an additional advantage of the API method. A feature that is not available in other methods.
That concludes the tutorial. Hope you enjoyed learning about these various methods and chose the best one for your upcoming project!