ellisio/laravel-phone

使用免费Twilio电话查找服务为Laravel提供的电话号码验证器。

v8.0.0 2020-03-10 18:50 UTC

This package is auto-updated.

Last update: 2024-09-11 05:01:53 UTC


README

Latest Stable Version License Total Downloads Build Status

介绍

为Laravel 6+提供的电话号码验证器,使用免费的Twilio Lookup API

此包为开发者提供了验证和格式化电话号码的能力。所有数据都将从Twilio Lookup API中提取。

验证可以配置为检查号码是否有效,或者是否在给定的ISO-3166-1 Alpha 2国家代码列表中有效。

安装

通过Composer安装

composer require ellisio/laravel-phone

将您的Twilio凭证添加到您的.env文件中。如果您没有Twilio账户,您可以免费注册一个在这里

TWILIO_ACCOUNT_SID=xxxxxxxx
TWILIO_AUTH_TOKEN=xxxxxxxx

配置

如果您想为此包自定义配置,可以通过以下命令将配置文件发布到/config/phone.php

php artisan vendor:publish --provider=EllisIO/Phone/PhoneServiceProvider --tag=laravel-phone-config

如果您想自定义验证消息的输出,可以通过以下命令将翻译文件发布到/lang/vendor/laravel-phone

php artisan vendor:publish --provider=EllisIO/Phone/PhoneServiceProvider --tag=laravel-phone-translations

使用

电话号码验证

如果您只需要验证给定的号码是否有效,请使用phone规则。

return [
    'phone' => 'required|phone',
];

国家验证

如果您需要验证给定的号码在某个国家列表中是否有效,请使用phone_country:US,CA规则。您可以列出任意数量的ISO-3166-1 Alpha 2国家代码,使用逗号分隔。

return [
    'phone' => 'required|phone_country:US,CA',
];

格式化电话号码

如果您想使用INTERNATIONAL_FORMAT格式化电话号码,请使用以下代码

Phone::formatNumber('5551234567');

创建电话号码对象

此库包括生成Phone对象的能力。该对象包含以下有关号码的详细信息

  • countryCode: ISO-3166 alpha 2国家代码。
  • number: E.164号码。
  • formattedNumber: 国家格式化号码。
$phone = Phone::getPhone('5551234567');
$phone->getNumber(); // Returns "+15551234567"
$phone->getNationalNumber(); // Returns "5551234567"
$phone->getFormattedNumber(); // Returns "(555) 123-4567"
$phone->getCountry(); // Returns "US"
$phone->getCountryCallingCode(); // Returns "1"

处理无效号码

有时您可能会遇到不良数据,这是常有的事。为了处理这种情况,只需检查是否返回了null

if (! $phone = Phone::getPhone('123')) {
    echo "Invalid number provided.";
}

支持

需要帮助?创建一个问题