Phonelib
Ruby gem for phone validation and formatting using google libphonenumber library data
Install / Use
/learn @daddyz/PhonelibREADME
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:
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 <tt>config/initializers/phonelib.rb</tt>:
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
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).
Phonelib.vanity_conversion = true
To disable sanitizing of passed phone number (keeping digits only)
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
Phonelib.ignore_plus = true
To change sanitized symbols on parsed number, so non-specified symbols won't be wiped and will fail the parsing
Phonelib.sanitize_regex = '[\.\-\(\) \;\+]'
To disable sanitizing of double prefix on passed phone number
Phonelib.strict_double_prefix_check = true
To set different extension separator on formatting, this setting doesn't affect parsing. Default setting is ';'
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.
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.
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:
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:
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:
validates :attribute, phone: { possible: true, allow_blank: true, types: [:voip, :mobile], country_specifier: -> phone { phone.country.try(:upcase) } }
<tt>possible: true</tt> - 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.
<tt>allow_blank: true</tt> - when no value passed then validation passes
<tt>types: :mobile</tt> or <tt>types: [:voip, :mobile]</tt> - allows to validate against specific phone types patterns, if mixed with <tt>possible</tt> will check if number is possible for specified type
<tt>countries: :us</tt> or <tt>countries: [:us, :ca]</tt> - allows to validate against specific countries, if mixed with <tt>possible</tt> will check if number is possible for specified countries
<tt>country_specifier: :method_name</tt> or <tt>country_specifier: -> instance { instance.country.try(:upcase) }</tt> - allows to specify country for validation dynamically for each validation. Usefull when phone is stored as national number without country prefix.
<tt>extensions: false</tt> - set to perform check for phone extension to be blank
Basic usage
To check if phone number is valid simply run:
Phonelib.valid?('123456789') # returns true or false
Additional methods:
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 <tt>'US'</tt> or <tt>'us'</tt> as well as symbol <tt>:us</tt>.
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:
phone = Phonelib.parse('123456789')
phone = Phonelib.parse('+1 (972) 123-4567', 'US')
You can pass phone number with extension, it should be separated with <tt>;</tt> or <tt>#</tt> signs from the phone number.
Returned value is object of <tt>Phonelib::Phone</tt> class which have following methods:
# 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
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:
- <tt>:premium_rate</tt> - Premium Rate
- <tt>:toll_free</tt> - Toll Free
- <tt>:shared_cost</tt> - Shared Cost
- <tt>:voip</tt> - VoIP
- <tt>:personal_number</tt> - Personal Number
- <tt>:pager</tt> - Pager
- <tt>:uan</tt> - UAN
- <tt>:voicemail</tt> - VoiceMail
- <tt>:fixed_line</tt> - Fixed Line
- <tt>:mobile</tt> - Mobile
- <tt>:fixed_or_mobile</tt> - Fixed Line or Mobile (if both mobile and fixed pattern matches)
- <tt>:short_code</tt>
- <tt>:emergency</tt>
- <tt>:carrier_specific</tt>
- <tt>:sms_services</tt>
- <tt>:expanded_emergency</tt>
- <tt>:no_international_dialling</tt>
- <tt>:carrier_services</tt>
- <tt>:directory_services</tt>
- <tt>:standard_rate</tt>
- <tt>:carrier_selection_codes</tt>
- <tt>:area_code_optional</tt>
Or you can get human representation of matched types
phone.human_types # return array of human representations of valid types
phone.human_type # return human representation of first valid type
Also you can fetch all matched countries
Related Skills
node-connect
345.9kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
106.4kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
345.9kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
345.9kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
