udokmeci/yii2-phone-validator

Modern Yii2 Phone validator wrapper on top of PhoneNumberUtil library also used by Android devices

Installs: 213 480

Dependents: 3

Suggesters: 0

Security: 0

Stars: 36

Watchers: 2

Forks: 17

Open Issues: 10

Type:yii2-extension

pkg:composer/udokmeci/yii2-phone-validator


README

Tests Code Quality Latest Stable Version Total Downloads License PHP Version

Yii2 phone number validator extension using Google's libphonenumber library.

Installation

composer require udokmeci/yii2-phone-validator

Usage

Basic Validation

use udokmeci\yii2PhoneValidator\PhoneValidator;

class Contact extends ActiveRecord
{
    public function rules()
    {
        return [
            [['phone'], PhoneValidator::class, 'country' => 'NL'],
        ];
    }
}

Using Format Enum

use udokmeci\yii2PhoneValidator\PhoneValidator;
use udokmeci\yii2PhoneValidator\PhoneNumberFormat;

// Modern PHP 8.1+ enum usage
public function rules()
{
    return [
        [['phone'], PhoneValidator::class, 
            'country' => 'NL',
            'format' => PhoneNumberFormat::E164        // Enum case
        ],
        [['mobile'], PhoneValidator::class,
            'country' => 'NL', 
            'format' => PhoneNumberFormat::INTERNATIONAL // Enum case
        ],
    ];
}

Dynamic Country Detection

public function rules()
{
    return [
        [['phone'], PhoneValidator::class, 'countryAttribute' => 'country_code'],
    ];
}

Custom Formatting

use udokmeci\yii2PhoneValidator\PhoneNumberFormat;

public function rules()
{
    return [
        [['phone'], PhoneValidator::class, 
            'country' => 'NL',
            'format' => PhoneNumberFormat::E164  // Using enum
        ],
    ];
}

Configuration

Property Description Default
country Fixed country code (ISO 3166-1 alpha-2) null
countryAttribute Model attribute containing country code null
strict Require country for validation true
format Output format INTERNATIONAL

Format Options

Format Example Output
PhoneNumberFormat::E164 +31612345678
PhoneNumberFormat::INTERNATIONAL +31 6 12345678
PhoneNumberFormat::NATIONAL 06 12345678
PhoneNumberFormat::RFC3966 tel:+31-6-12345678
false No formatting

Note: PhoneNumberFormat is a modern PHP 8.1+ enum. Import: use udokmeci\yii2PhoneValidator\PhoneNumberFormat;

Examples

Netherlands Phone

// Input: '0612345678'
// Output: '+31 6 12345678'

US Phone

[['phone'], PhoneValidator::class, 'country' => 'US']
// Input: '2125551234' 
// Output: '+1 212 555 1234'

Non-Strict Mode

[['phone'], PhoneValidator::class, 'strict' => false]
// Validates only if country is available

Requirements

  • PHP 8.1+
  • Yii2 2.0.40+
  • giggsey/libphonenumber-for-php ^8.13

Testing

Follow Yii2 Extension Testing Guidelines:

vendor/bin/phpunit
vendor/bin/phpstan analyse  
vendor/bin/phpcs --standard=PSR12 src/

License

MIT License. See LICENSE file.