Evgenii Goryaev aka floor12
Development of complicated web projects.

floor12/yii2-phone: Validator and formatter for phone numbers.

Build Status Latest Stable Version Latest Unstable Version Total Downloads License Formatter and validator form phone numbers.

Installation

To use this extension run this command:

 $ composer require floor12/yii2-phone

or add this to the require section of your composer.json.

 "floor12/yii2-phone": "dev-master"

Usage

This extension allows to validate phone numbers and save only numbers in DB without any formatting. It also includes simple formatter to render formatted phone numbers as a string or HTML <a href='tel:'> tag.

Phone validation

To store phone numbers in the database, the ActiveRecord model database field should be VARCHAR(12).

The validator has backend and frontend (js) validation. To validate your field, add floor12\phone\PhoneValidator to ActiveRecord::rules() action like this:

use floor12\phone\PhoneValidator;
use yii\base\Model;

class User extends Model
{

    public $phone;

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

Phone formatting

Class floor12\phone\PhoneFormatter allows to render phone number as formatted string or as html <a href="tel:">, and has two static methods:

  • PhoneFormatter::format($phone)
  • PhoneFormatter::a($phone,array $options= [])

Formatting examples

echo PhoneFormatter::format(79461234565);                       # +7 (946) 123-45-65
echo PhoneFormatter::a(79461234565);                            # <a href='tel:+79461234565'>+7 (946) 123-45-65</a>
echo PhoneFormatter::a(79461234565,['class'=>'phone-link']);    # <a href='tel:+79461234565' class='phone-link'>+7 (946) 123-45-65</a>