Ruby gem for phone validation and formatting using google libphonenumber library data
Ruby gem for phone validation and formatting using google libphonenumber library data
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.
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.
Change log can be found in repo's releases page https://github.com/daddyz/phonelib/releases
If you discover a problem with Phonelib gem, let us know about it. https://github.com/daddyz/phonelib/issues
You can see an example of ActiveRecord validation by phonelib working in spec/dummy application of this gem
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 config/initializers/phonelib.rb:
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 = trueTo 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 = trueTo disable sanitizing of passed phone number (keeping digits only)
Phonelib.strict_check = trueTo 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 = trueTo 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 = trueTo 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 separatorIn 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.
This gem adds validator for active record. Basic usage:
validates :attribute, phone: trueThis 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) } }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.
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:
es:
errors:
messages:
phone_too_short: "es demasiado corto"
phone_invalid: "no es un número telefónico válido"To check if phone number is valid simply run:
Phonelib.valid?('123456789') # returns true or falseAdditional 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 numberThere 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.
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 countryAdditionally you can run:
phone = Phonelib.parse('123456789')
phone = Phonelib.parse('+1 (972) 123-4567', 'US')Parsed phones expose immutable validation diagnostics without requiring Rails:
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 APIUse validation when the result or a validation policy is also needed:
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 :impossiblepossible_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:
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:
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:
# 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 typesPossible types:
No open issues yet, or sync has not completed.