PHPackages                             nanayawkumi/gh-phone-validator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. nanayawkumi/gh-phone-validator

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

nanayawkumi/gh-phone-validator
==============================

Laravel validation rule and helpers for Ghana phone numbers

v1.3.0(4mo ago)0152↓50%MITPHPPHP ^8.2

Since Dec 21Pushed 4mo agoCompare

[ Source](https://github.com/nanayawkumi/gh-phone-validator)[ Packagist](https://packagist.org/packages/nanayawkumi/gh-phone-validator)[ RSS](/packages/nanayawkumi-gh-phone-validator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (4)Versions (5)Used By (0)

Gh Phone Validator
==================

[](#gh-phone-validator)

A Laravel validation rule and helper package for validating and normalizing Ghana phone numbers.

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require nanayawkumi/gh-phone-validator
```

The package will automatically register its service provider if you're using Laravel's package auto-discovery.

Requirements
------------

[](#requirements)

- PHP ^8.2
- Laravel ^10.0|^11.0|^12.0

Usage
-----

[](#usage)

### Validation Rule

[](#validation-rule)

You can use the `gh_phone` validation rule in your form requests or controllers:

```
use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'phone' => 'required|gh_phone',
]);
```

Or use the rule class directly:

```
use Nanayawkumi\GhPhoneValidator\Rules\GhPhone;

$validator = Validator::make($request->all(), [
    'phone' => ['required', new GhPhone()],
]);
```

### Normalize Phone Numbers

[](#normalize-phone-numbers)

The `normalize()` method converts various phone number formats to a standard 10-digit format (starting with 0):

```
use Nanayawkumi\GhPhoneValidator\GhPhoneValidator;

GhPhoneValidator::normalize('241234567');        // Returns: '0241234567'
GhPhoneValidator::normalize('+233241234567');    // Returns: '0241234567'
GhPhoneValidator::normalize('233241234567');     // Returns: '0241234567'
GhPhoneValidator::normalize('024-123-4567');     // Returns: '0241234567'
GhPhoneValidator::normalize('024 123 4567');     // Returns: '0241234567'
GhPhoneValidator::normalize('invalid');          // Returns: null
```

### Detect Network

[](#detect-network)

The `network()` method identifies the network provider for a given phone number and returns a `Network` enum:

```
use Nanayawkumi\GhPhoneValidator\GhPhoneValidator;
use Nanayawkumi\GhPhoneValidator\Enums\Network;

$network = GhPhoneValidator::network('0241234567');
// Returns: Network::MTN

$network = GhPhoneValidator::network('0201234567');
// Returns: Network::TELECEL

$network = GhPhoneValidator::network('0261234567');
// Returns: Network::AIRTELTIGO

$network = GhPhoneValidator::network('invalid');
// Returns: null
```

For backward compatibility, you can also use `networkInfo()` to get the array format:

```
$network = GhPhoneValidator::networkInfo('0241234567');
// Returns: ['name' => 'MTN', 'slug' => 'mtn']
```

### Validate Phone Numbers

[](#validate-phone-numbers)

The `validate()` method checks if a phone number is valid (10 digits and starts with a valid network prefix):

```
use Nanayawkumi\GhPhoneValidator\GhPhoneValidator;

GhPhoneValidator::validate('0241234567');  // Returns: true
GhPhoneValidator::validate('0201234567');  // Returns: true
GhPhoneValidator::validate('9991234567');  // Returns: false (invalid prefix)
GhPhoneValidator::validate('12345');       // Returns: false (invalid length)
```

### Format Phone Numbers

[](#format-phone-numbers)

The package provides several formatting methods to display phone numbers in different formats:

#### Raw Local Format

[](#raw-local-format)

The `formatRaw()` method returns the phone number in raw local format (10 digits starting with 0):

```
use Nanayawkumi\GhPhoneValidator\GhPhoneValidator;

GhPhoneValidator::formatRaw('+233241234567');  // Returns: '0241234567'
GhPhoneValidator::formatRaw('024 123 4567');   // Returns: '0241234567'
GhPhoneValidator::formatRaw('invalid');        // Returns: null
```

#### National Format

[](#national-format)

The `formatNational()` method formats the phone number with spaces for readability:

```
use Nanayawkumi\GhPhoneValidator\GhPhoneValidator;

GhPhoneValidator::formatNational('0241234567');     // Returns: '024 123 4567'
GhPhoneValidator::formatNational('+233241234567');  // Returns: '024 123 4567'
GhPhoneValidator::formatNational('invalid');         // Returns: null
```

#### International Format

[](#international-format)

The `formatInternational()` method formats the phone number in international readable format:

```
use Nanayawkumi\GhPhoneValidator\GhPhoneValidator;

GhPhoneValidator::formatInternational('0241234567');     // Returns: '+233 24 123 4567'
GhPhoneValidator::formatInternational('+233241234567');  // Returns: '+233 24 123 4567'
GhPhoneValidator::formatInternational('invalid');         // Returns: null
```

#### E.164 Format

[](#e164-format)

The `formatE164()` method formats the phone number in E.164 international format:

```
use Nanayawkumi\GhPhoneValidator\GhPhoneValidator;

GhPhoneValidator::formatE164('0241234567');     // Returns: '+233241234567'
GhPhoneValidator::formatE164('024 123 4567');   // Returns: '+233241234567'
GhPhoneValidator::formatE164('invalid');        // Returns: null
```

### Common Use Cases

[](#common-use-cases)

#### UI Display

[](#ui-display)

Format phone numbers for display in your user interface:

```
{{ $user->phone }}                    {{-- Raw format: 0241234567 --}}
{{ $user->phone->national() }}        {{-- National: 024 123 4567 --}}
{{ $user->phone->international() }}   {{-- International: +233 24 123 4567 --}}
```

#### SMS / Telco APIs

[](#sms--telco-apis)

Format phone numbers in E.164 format for SMS gateways and telco APIs:

```
// Using the cast
$msisdn = $user->phone->e164();

// Or using the validator directly
$msisdn = GhPhoneValidator::formatE164($phone);
```

Eloquent Cast
-------------

[](#eloquent-cast)

This package provides an Eloquent cast for Ghana phone numbers.

### Basic Usage

[](#basic-usage)

```
use Nanayawkumi\GhPhoneValidator\Casts\GhPhoneCast;

class User extends Model
{
    protected $casts = [
        'phone' => GhPhoneCast::class,
    ];
}
```

### Behavior

[](#behavior)

- **Accepts messy input when saving**: The cast automatically normalizes various phone number formats (with spaces, dashes, international format, etc.) when saving to the database.
- **Stores numbers in raw format by default**: Phone numbers are stored in the database using the raw local format (e.g., `0241234567`). You can optionally store in E.164 format using `:e164`.
- **Works as string and value object**: When retrieving the phone number, `$user->phone` works as a string (returns raw format) and also provides formatting methods:

```
// Direct string access (returns raw format)
echo $user->phone;                // Output: '0241234567'
$phone = $user->phone;            // String: '0241234567'

// Formatting methods
$user->phone->national();         // Returns: '024 123 4567'
$user->phone->international();   // Returns: '+233 24 123 4567'
$user->phone->e164();            // Returns: '+233241234567'
$user->phone->network();         // Returns: Network::MTN (enum)
$user->phone->raw();             // Returns: '0241234567'
```

**Example:**

```
// Saving with messy input
$user = new User();
$user->phone = '024 123 4567';  // Accepts various formats
$user->save();                   // Stored as '0241234567' (raw format)

// Retrieving and using
$user = User::find(1);

// Use as string (automatically returns raw format)
echo $user->phone;                    // Output: '0241234567'

// Use formatting methods
echo $user->phone->national();        // Output: '024 123 4567'
echo $user->phone->international();  // Output: '+233 24 123 4567'
echo $user->phone->e164();           // Output: '+233241234567'
```

Cast Storage Customization
--------------------------

[](#cast-storage-customization)

You can control how phone numbers are stored in the database.

### Store as Raw Local Format (default)

[](#store-as-raw-local-format-default)

```
use Nanayawkumi\GhPhoneValidator\Casts\GhPhoneCast;

protected $casts = [
    'phone' => GhPhoneCast::class,
];
```

Phone numbers are stored in raw local format (e.g., `0241234567`) by default.

### Store as E.164 Format

[](#store-as-e164-format)

```
use Nanayawkumi\GhPhoneValidator\Casts\GhPhoneCast;

protected $casts = [
    'phone' => GhPhoneCast::class . ':e164',
];
```

Phone numbers are stored in E.164 international format (e.g., `+233241234567`).

### Notes

[](#notes)

- **All formats are normalized before storage**: Regardless of the input format (with spaces, dashes, international format, etc.), the phone number is normalized before being stored.
- **Retrieval returns a value object that works as string**: When retrieving from the database, you get a `PhoneNumber` value object that works as a string (returns raw format) and also provides formatting methods, regardless of how it was stored.
- **Strict mode is respected**: The cast respects the strict mode configuration when validating phone numbers before storage.

**Example:**

```
// Store as raw (default)
$user = new User();
$user->phone = '024 123 4567';
$user->save();  // Stored as '0241234567'

// Store as E.164 format
use Nanayawkumi\GhPhoneValidator\Casts\GhPhoneCast;

class User extends Model
{
    protected $casts = [
        'phone' => GhPhoneCast::class . ':e164',
    ];
}

$user = new User();
$user->phone = '024 123 4567';
$user->save();  // Stored as '+233241234567'

// Retrieval works the same way regardless of storage format
$user = User::find(1);
echo $user->phone;                // Output: '0241234567' (always raw when used as string)
echo $user->phone->e164();        // Output: '+233241234567'
```

Network Enum
------------

[](#network-enum)

The package provides a strongly-typed `Network` enum for working with network providers.

### Using the Network Enum

[](#using-the-network-enum)

```
use Nanayawkumi\GhPhoneValidator\GhPhoneValidator;
use Nanayawkumi\GhPhoneValidator\Enums\Network;

$network = GhPhoneValidator::network('0241234567');

if ($network === Network::MTN) {
    // Do something
}

$network->label(); // MTN
$network->slug();  // mtn
```

### From Eloquent Cast

[](#from-eloquent-cast)

When using the Eloquent cast, the `network()` method returns a `Network` enum:

```
use Nanayawkumi\GhPhoneValidator\Enums\Network;

$user->phone->network(); // Network enum (Network::MTN, Network::TELECEL, etc.)

// Use it in conditionals
if ($user->phone->network() === Network::MTN) {
    // User is on MTN network
}

// Get network label
echo $user->phone->network()?->label(); // MTN

// Get network slug
echo $user->phone->network()?->slug();  // mtn
```

### Available Methods

[](#available-methods)

The `Network` enum provides the following methods:

- `label()` - Returns the human-readable network name (e.g., "MTN", "Telecel")
- `slug()` - Returns the network slug (e.g., "mtn", "telecel")
- `codes()` - Returns an array of network prefix codes
- `fromPhone(string $phone)` - Static method to get network from a phone number

**Example:**

```
use Nanayawkumi\GhPhoneValidator\Enums\Network;

$network = Network::fromPhone('0241234567');

if ($network) {
    echo $network->label();        // MTN
    echo $network->slug();        // mtn
    print_r($network->codes());    // ['024', '054', '055', ...]
}
```

Supported Networks
------------------

[](#supported-networks)

The package recognizes the following network providers:

- **MTN**: 024, 054, 055, 059, 025, 053, 023
- **Telecel**: 020, 050
- **AirtelTigo**: 026, 056, 027, 057

Configuration
-------------

[](#configuration)

Publish the configuration file to customize network settings:

```
php artisan vendor:publish --tag=gh-phone-validator-config
```

This will create a `config/gh-phone-validator.php` file where you can modify network codes and names.

### Strict Mode

[](#strict-mode)

Strict mode controls whether the package accepts phone numbers with unknown network prefixes:

- **Enabled (`strict => true`)**: Only accepts phone numbers with prefixes that match known network codes. Numbers with unknown prefixes will return `null` when normalized.
- **Disabled (`strict => false`)**: Accepts any valid 10-digit Ghana phone number starting with 0, even if the prefix isn't in the known networks list.

```
// In config/gh-phone-validator.php
'strict' => true,  // Reject unknown prefixes
'strict' => false, // Accept any valid 10-digit number (default)
```

**Example:**

```
// With strict mode enabled
config()->set('gh-phone-validator.strict', true);
GhPhoneValidator::normalize('0291234567');  // Returns: null (unknown prefix)

// With strict mode disabled
config()->set('gh-phone-validator.strict', false);
GhPhoneValidator::normalize('0291234567');  // Returns: '0291234567' (accepted)
```

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

Author
------

[](#author)

Samuel Kumi-Buabeng

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance76

Regular maintenance activity

Popularity14

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

4

Last Release

133d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/35550119?v=4)[Nana Yaw Kumi-Buabeng](/maintainers/nanayawkumi)[@nanayawkumi](https://github.com/nanayawkumi)

---

Top Contributors

[![nanayawkumi](https://avatars.githubusercontent.com/u/35550119?v=4)](https://github.com/nanayawkumi "nanayawkumi (5 commits)")

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/nanayawkumi-gh-phone-validator/health.svg)

```
[![Health](https://phpackages.com/badges/nanayawkumi-gh-phone-validator/health.svg)](https://phpackages.com/packages/nanayawkumi-gh-phone-validator)
```

###  Alternatives

[propaganistas/laravel-phone

Adds phone number functionality to Laravel based on Google's libphonenumber API.

3.0k35.7M107](/packages/propaganistas-laravel-phone)[spatie/laravel-honeypot

Preventing spam submitted through forms

1.6k6.0M60](/packages/spatie-laravel-honeypot)[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[axlon/laravel-postal-code-validation

Worldwide postal code validation for Laravel and Lumen

3853.3M1](/packages/axlon-laravel-postal-code-validation)[wendelladriel/laravel-validated-dto

Data Transfer Objects with validation for Laravel applications

759569.4k13](/packages/wendelladriel-laravel-validated-dto)[sunspikes/clamav-validator

Custom Laravel 5 anti-virus validator for file uploads.

3651.8M3](/packages/sunspikes-clamav-validator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
