Guides
Last updated
July 20, 2025

5 Methods for Phone Number Validation in Laravel

Nicolas Rios
Nicolas Rios
Table of Contents:
ON THIS PAGE
Get your free
phone validation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Validating phone numbers is a common requirement for maintaining data quality in any Laravel application. We will explore five methods for implementation, providing working code snippets for each. Along the way, we'll examine the drawbacks of these approaches and how Abstract API can overcome them.

Laravel Phone Number Validation Methods

Here are four common approaches to phone number validation in a Laravel application, from a simple regular expression to the use of a dedicated community package.

Built-in Validator with a Regular Expression

Laravel's validator allows the use of regular expressions for custom rules. This approach defines a pattern that the input phone number must match to pass validation.

The code specifies a rule for a 'phone' field. The regex pattern checks for an E.164 format, which starts with an optional '+' sign, a country code, and then 1 to 14 additional digits.

rules():
    return [
        'phone' => [
            'required',
            // + country code, then 1-14 digits (E.164 hard limit is 15)
            'regex:/^\\+?[1-9]\\d{1,14}$/'
        ],
    ];

A Dedicated Rule Object

A more structured approach involves the creation of a dedicated Rule object. You can generate this file with the `php artisan make:rule ValidPhone` command. This encapsulates the validation logic into a reusable class.

The `ValidPhone` class implements Laravel's `Rule` interface and uses the `libphonenumber` library. The `passes` method attempts to parse the number against a specified region, like 'US', and returns true if the library considers it valid.

// In app/Rules/ValidPhone.php
class ValidPhone implements Rule
{
    public function __construct(private string $region = 'US') {}

    public function passes($attribute, $value): bool
    {
        $u = \libphonenumber\PhoneNumberUtil::getInstance();
        try {
            $p = $u->parse($value, $this->region);
            return $u->isValidNumber($p);
        } catch (\libphonenumber\NumberParseException) {
            return false;
        }
    }

    public function message(): string
    {
        return 'Invalid phone number for region '.$this->region.'.';
    }
}

// Usage in a FormRequest
'phone' => ['required', new ValidPhone('US')];

A Global Validator Macro

For application-wide reuse, you can define a global validator macro. This is typically done within the `boot` method of a service provider, such as the `AppServiceProvider`.

This approach extends Laravel's `Validator` facade with a new rule, here named `phone_global`. The rule's logic uses `libphonenumber` and becomes available anywhere in your app. You can pass parameters like the region code directly in the validation rule string.

// In AppServiceProvider::boot()
Validator::extend('phone_global', function ($attribute, $value, $parameters) {
    $region = $parameters[0] ?? null;
    $u = \libphonenumber\PhoneNumberUtil::getInstance();
    try {
        return $u->isValidNumber($u->parse($value, $region));
    } catch (\Throwable) {
        return false;
    }
});

// Usage in a FormRequest
'phone' => 'required|phone_global:US';

The Propaganistas/Laravel-Phone Package

A popular option is to use a pre-built, community-maintained package. The `propaganistas/laravel-phone` package is a well-regarded choice that you install with Composer.

This package provides a `phone` validation rule that builds upon `libphonenumber`. It offers features like multi-country validation, automatic country detection, attribute casting, and formatting helpers.

// Install with Composer
composer require propaganistas/laravel-phone

// Usage in a FormRequest
'phone' => 'required|phone:US,CA',
// or dynamic: 'phone' => (new \Propaganistas\LaravelPhone\Rules\Phone)->country(['US','CA'])

Challenges of Laravel Phone Number Validation

While these methods seem straightforward, they introduce significant reliability and security issues. Each approach presents unique drawbacks that can compromise data integrity and application stability.

  • Methods that rely on libphonenumber, like a Rule object or global macro, require constant metadata updates. Without them, changes in global numbering plans and number portability lead to false positives or negatives.
  • The propaganistas/laravel-phone package can be fragile. Minor updates sometimes introduce uncaught errors or cause the validator to ignore rules like nullable, which can crash a request instead of return a simple validation error.
  • All methods, from a simple regex to a dedicated package, only check format. They cannot confirm a number is active or prevent the use of disposable numbers, which leaves applications open to bot sign-ups and fraud.
  • Model-level casts from the propaganistas/laravel-phone package create brittle code. An incorrect field assignment order during mass updates can trigger exceptions before the validator even runs, which makes the entire flow fragile.

Validate Phone Numbers with Abstract API
Implement phone number validation in your Laravel project to collect accurate and reliable user data.
Get started for free

How Abstract API Handles Phone Number Validation in Laravel

Abstract API addresses the core weaknesses of traditional validation methods. It externalizes the complex and ever-changeable rules associated with phone numbers.

  • It uses an up-to-date carrier and numbering-plan database for over 195 countries. This provides real-time correctness instead of static pattern checks.
  • The API response includes E.164 and local formats, country metadata, line type, carrier, and region. This data allows for downstream decisions like how to route SMS or tag high-risk geographies.
  • It offers a simple HTTP interface. A single GET request with your key and the phone number integrates easily with Laravel’s built-in HTTP client.
  • Predictable errors and status codes let you plug the call directly into Laravel’s validation flow. This helps bubble up user-friendly messages.

How to Add Abstract API to Your Dev Environment

Once you understand Abstract’s capabilities, to add its phone number validation API to your project is simple. The process involves a few configuration steps to connect your Laravel application to the service.

  • Sign up at Abstract API, enable the Phone Validation API, and copy your key.
  • Add the key to your .env file as ABSTRACT_PHONE_KEY and reference it in config/services.php.
  • Ensure Laravel’s HTTP client is available. The framework already includes Guzzle in versions 7 and up.
  • Create a service class, for example app/Services/PhoneValidator.php, to wrap the API call.
  • Register a custom validation rule or use a Form Request that calls your new service and checks the response.
  • Add automated tests that use the Abstract sandbox or mock the service to maintain a deterministic CI pipeline.

Sample Phone Number Validation Implementation with Abstract API

You can integrate the API call directly into a Laravel Form Request. This allows you to validate the phone number before your controller logic executes. The code sends the user-provided phone number to Abstract API and checks the boolean `valid` field in the response. If the number is not valid, it throws a standard validation exception with a user-friendly error message.

$response = Http::get('https://phonevalidation.abstractapi.com/v1/', [
    'api_key' => config('services.abstract_phone.key'),
    'phone'   => $this->input('phone'),
]);

if (!$response->json('valid')) {
    throw ValidationException::withMessages(['phone' => 'Phone number is not valid.']);
}

A successful API call returns a rich JSON object. This data confirms the number is dialable and provides useful context. You get both a storage-safe E.164 format and a local format for display. The response also includes country, location, line type, and carrier details. This information enables you to build advanced, geo-based rules or workflows.

{
  "phone": "14152007986",
  "valid": true,
  "format": {
    "international": "+14152007986",
    "local": "(415) 200-7986"
  },
  "country": {
    "code": "US",
    "name": "United States",
    "prefix": "+1"
  },
  "location": "California",
  "type": "mobile",
  "carrier": "T-Mobile USA, Inc."
}

Final Thoughts

Traditional methods that use regex patterns or local libraries often fail. They cannot handle diverse international formats or guarantee a number is active. Abstract API solves these issues with a real-time, global database and provides rich contextual data for every number. Consider an account with Abstract API to get your free key and reliably validate phone numbers.

Validate Phone Numbers with Abstract API
Validate phone numbers in your Laravel project to improve data quality and stop fake users.
Get started for free

Related Articles

Phone Validation
key now
Get your free
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required