Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

phonelib

> 编程语言
Open source

Ruby gem for phone validation and formatting using google libphonenumber library data

1.2K stars0 likes0 views
WebsiteGitHub

About

Ruby gem for phone validation and formatting using google libphonenumber library data

Phonelib

Phonelib is a gem allowing you to validate phone number. All validations are based on Google libphonenumber. Currently it can make basic validations and formatting to e164 international number format and national number format with prefix. But it still doesn't include all Google's library functionality.

Incorrect parsing or validation

In case your phone number is incorrectly parsed, you can check original libphonenumber for result here and in case of same parse result open an issue for them. This gem's data is based on it. If you can't wait for libphonenumber to resolve the issue, try to use Phonelib.add_additional_regex and Phonelib.additional_regexes methods.

Information

Change Log

Change log can be found in repo's releases page https://github.com/daddyz/phonelib/releases

Bug reports

If you discover a problem with Phonelib gem, let us know about it. https://github.com/daddyz/phonelib/issues

Example application

You can see an example of ActiveRecord validation by phonelib working in spec/dummy application of this gem

Getting started

Phonelib was written and tested on Rails >= 3.1. You can install it by adding in to your Gemfile with:

ruby
gem 'phonelib'

Run the bundle command to install it.

To set the default country or several default countries for parsing (country names are ISO 3166-1 Alpha-2 codes), create a initializer in config/initializers/phonelib.rb:

ruby
Phonelib.default_country = "CN"
Phonelib.default_country = ['CN', 'FR']

To use the ability to parse special numbers (Short Codes, Emergency etc.) you can set Phonelib.parse_special. This is disabled by default

ruby
Phonelib.parse_special = true

To allow vanity phone numbers conversion you can set Phonelib.vanity_conversion to true. This will convert characters in passed phone number to their numeric representation (800-CALL-NOW will be 800-225-5669).

ruby
Phonelib.vanity_conversion = true

To disable sanitizing of passed phone number (keeping digits only)

ruby
Phonelib.strict_check = true

To disable country reset during parsing in case phone starts with + sign and country specified but country phone prefix doesn't match phone's prefix

ruby
Phonelib.ignore_plus = true

To change sanitized symbols on parsed number, so non-specified symbols won't be wiped and will fail the parsing

ruby
Phonelib.sanitize_regex = '[\.\-\(\) \;\+]'

To disable sanitizing of double prefix on passed phone number

ruby
Phonelib.strict_double_prefix_check = true

To set different extension separator on formatting, this setting doesn't affect parsing. Default setting is ';'

ruby
Phonelib.extension_separator = ';'

To set symbols that are used for separating extension from phone number for parsing use Phonelib.extension_separate_symbols method. Default value is '#;'. In case string is passed each one of the symbols in the string will be treated as possible separator, in case array was passed each string in array will be treated as possible separator.

ruby
Phonelib.extension_separate_symbols = '#;'           # for single symbol separator
Phonelib.extension_separate_symbols = %w(ext # ; extension) # each string will be treated as separator

In case you need to overwrite some Google's libphonenumber library data, you need to assign file path to this setter. File should be Marshal.dump'ed with existing structure like in Phonelib.phone_data. Gem is simply doing merge between hashes.

ruby
Phonelib.override_phone_data = '/path/to/override_phone_data.dat'

In case you want to add some custom or still not updated regex patterns for certain type you can use additional regexes feature in a following way:

ruby
Phonelib.add_additional_regex :us, Phonelib::Core::MOBILE, '[5]{10}' # this will add number 1-555-555-5555 to be valid
Phonelib.add_additional_regex :gb, Phonelib::Core::MOBILE, '[1]{5}' # this will add number 44-11-111 to be valid
# you can also specify all regexes using this method
Phonelib.additional_regexes = [[:us, :mobile, "[5]{10}"], [:gb, :mobile, "[1]{5}"]]
# or just use dump method to keep them altogether
Phonelib.dump_additional_regexes # => [["US", :mobile, "[5]{10}"], ["GB", :mobile, "[1]{5}"]

(!) For a list of available types refer to this readme.

(!) Please note that regex should be added as string

In case phone number that was passed for parsing has "+" sign in the beginning, library will try to detect a country regarding the provided one.

ActiveRecord Integration

This gem adds validator for active record. Basic usage:

ruby
validates :attribute, phone: true

This will enable Phonelib validator for field "attribute". This validator checks that passed value is valid phone number. Please note that passing blank value also fails.

Additional options:

ruby
validates :attribute, phone: { possible: true, allow_blank: true, types: [:voip, :mobile], country_specifier: -> phone { phone.country.try(:upcase) } }

possible: true - enables validation to check whether the passed number is a possible phone number (not strict check). Refer to Google libphonenumber for more information on it.

allow_blank: true - when no value passed then validation passes

types: :mobile or types: [:voip, :mobile] - allows to validate against specific phone types patterns, if mixed with possible will check if number is possible for specified type

countries: :us or countries: [:us, :ca] - allows to validate against specific countries, if mixed with possible will check if number is possible for specified countries

country_specifier: :method_name or country_specifier: -> instance { instance.country.try(:upcase) } - allows to specify country for validation dynamically for each validation. Usefull when phone is stored as national number without country prefix.

extensions: false - set to perform check for phone extension to be blank

require_international_prefix: true - requires the original value to use + or 00 as its explicit international marker. The marker may follow leading formatting characters recognized by the parser. This option does not change the parser or the formatted output.

format: :e164 - requires the original value to match Phonelib's canonical +-prefixed E.164 representation: 2 to 15 total ASCII digits, beginning with 1-9, with no spaces, punctuation, or extension. Unsupported formats raise an ArgumentError when the validator is configured.

detailed_errors: true - adds a specific, namespaced ActiveModel error for each failed phone rule. It is opt-in; without it the validator keeps adding the single :invalid error used by previous Phonelib versions. Enabling it changes error reporting only, not which values the existing validator accepts.

ruby
validates :phone, phone: {
  types: :mobile,
  countries: :us,
  extensions: false,
  detailed_errors: true
}

record.errors.details[:phone] # ActiveModel 5+
# [{ error: :phone_type_not_allowed, allowed_types: [:mobile], ... }]

record.errors.messages[:phone]
# ["has a phone type that is not allowed"]

record.errors.full_messages
# ["Phone has a phone type that is not allowed"]

On older ActiveModel versions, the detailed types still drive translated errors.messages, but Errors#details is not provided by the framework.

Detailed ActiveModel error types are prefixed with phone_ so they do not collide with generic Rails errors such as :too_short. Phonelib ships English defaults for every detailed error. Applications can override them through the normal I18n hierarchy, for example:

yaml
es:
  errors:
    messages:
      phone_too_short: "es demasiado corto"
      phone_invalid: "no es un número telefónico válido"

Basic usage

To check if phone number is valid simply run:

ruby
Phonelib.valid?('123456789') # returns true or false

Additional methods:

ruby
Phonelib.valid? '123456789'      # checks if passed value is valid number
Phonelib.invalid? '123456789'    # checks if passed value is invalid number
Phonelib.possible? '123456789'   # checks if passed value is possible number
Phonelib.impossible? '123456789' # checks if passed value is impossible number

There is also option to check if provided phone is valid for specified country. Country should be specified as two letters country code (like "US" for United States). Country can be specified as String 'US' or 'us' as well as symbol :us.

ruby
Phonelib.valid_for_country? '123456789', 'XX'   # checks if passed value is valid number for specified country
Phonelib.invalid_for_country? '123456789', 'XX' # checks if passed value is invalid number for specified country

Additionally you can run:

ruby
phone = Phonelib.parse('123456789')
phone = Phonelib.parse('+1 (972) 123-4567', 'US')

Parsed phones expose immutable validation diagnostics without requiring Rails:

ruby
phone = Phonelib.parse('+1 253000')

phone.errors.details
# [{ error: :too_short, actual_length: 6, expected_lengths: [10] }]

phone.errors.messages
# ["is too short"]

phone.errors.full_messages
# ["is too short"] # no model attribute exists in the core API

Use validation when the result or a validation policy is also needed:

ruby
result = phone.validation(
  possible: true,
  types: :mobile,
  countries: [:us, :ca],
  extensions: false
)

result.valid?       # whether all requested rules passed
result.invalid?
result.phone        # the same parsed Phone instance
result.errors       # Phonelib::Errors
result.error        # first ValidationError, or nil
result.possibility  # :possible, :possible_local_only, or :impossible

possible_local_only means the number has a length that can be dialed within its local area but lacks the information required for general dialing. It is exposed as diagnostic context; validation(possible: true) still follows the existing Phone#possible? result and therefore reports :not_possible for a local-only number.

Core diagnostic codes are deliberately short because they already live in Phonelib::ValidationError:

  • :not_a_number
  • :invalid_country_code
  • :too_short
  • :too_long
  • :invalid_length
  • :not_possible
  • :invalid
  • :type_not_allowed
  • :country_not_allowed
  • :extension_not_allowed

Successful validity and possibility are represented by the result, not by error codes.

Messages can be translated in plain Ruby without adding an I18n dependency to Phonelib. Pass any callable that accepts an I18n-style key and keyword values:

ruby
translator = -> key, default:, **values do
  I18n.t(key, default: default, **values)
end

phone.errors.messages(translator: translator)

You can pass phone number with extension, it should be separated with ; or # signs from the phone number.

Returned value is object of Phonelib::Phone class which have following methods:

ruby
# basic validation methods
phone.valid?
phone.invalid?
phone.possible?
phone.impossible?

# validations for countries
phone.valid_for_country? 'XX'
phone.invalid_for_country? 'XX'

You can also fetch matched valid phone types

ruby
phone.types          # returns array of all valid types
phone.type           # returns first element from array of all valid types
phone.possible_types # returns array of all possible types

Possible types:

  • :premium_rate - Premium Rate
  • :toll_free - Toll Free
  • :shared_cost - Shared Cost
  • :voip - VoIP
  • :personal_number - Personal Number
  • :pager - Pager
  • :uan - UAN
  • :voicemail - VoiceMail
  • :fixed_line - Fixed Line
  • :mobile - Mobile
  • :fixed_or_mobile - Fixed Line or Mobile (if both mobile and fixed pattern matches)
  • :short_co

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubygoogle-libphonenumberparsingphone-numberphone-parse

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言