Giter VIP home page Giter VIP logo

phonelib's Introduction

Phonelib

Built in integration with JetBrains RubyMine Gem Version CircleCI Inline docs

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 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 = 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) } }

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

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 '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 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 ; 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 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_code
  • :emergency
  • :carrier_specific
  • :sms_services
  • :expanded_emergency
  • :no_international_dialling
  • :carrier_services
  • :directory_services
  • :standard_rate
  • :carrier_selection_codes
  • :area_code_optional

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

phone.countries       # returns array of all matched countries
phone.country         # returns first element from array of all matched countries
phone.valid_countries # returns array of countries where phone was matched against valid pattern
phone.valid_country   # returns first valid country from array of valid countries
phone.country_code    # returns country phone prefix

Also it is possible to get formatted phone number

phone.international      # returns formatted e164 international phone number
phone.national           # returns formatted national number with national prefix
phone.area_code          # returns area code of parsed number or nil
phone.local_number       # returns local number
phone.extension          # returns extension provided with phone
phone.full_e164          # returns e164 phone representation with extension
phone.full_international # returns formatted international number with extension

You can pass false to national and international methods in order to get unformatted representations

phone.international(false) # returns unformatted international phone
phone.national(false)      # returns unformatted national phone

You can get E164 formatted number

phone.e164 # returns number in E164 format

You can define prefix for international and e164 related methods to get formatted number prefixed with anything you need.

phone.international('00')      # returns formatted international number prefixed by 00 instead of +
phone.e164('00')               # returns e164 represantation of a number prefixed by 00 instead of +
phone.full_international('00') # returns formatted international number with extension prefixed by 00 instead of +
phone.full_e164('00')          # returns e164 represantation of a number with extension prefixed by 00 instead of +
phone.international_00         # same as phone.international('00'). 00 can be replaced with whatever you need
phone.e164_00                  # same as phone.international('00') 

There is a to_s method, it will return e164 in case number is valid and original otherwise

phone.to_s # returns number in E164 format if number is valid or original otherwise

You can compare 2 instances of Phonelib::Phone with == method or just use it with string

phone1 = Phonelib.parse('+12125551234') # Phonelib::Phone instance
phone2 = Phonelib.parse('+12125551234') # Phonelib::Phone instance
phone1 == phone2                        # returns true
phone1 == '+12125551234'                # returns true
phone1 == '12125551234;123'             # returns true

There is extended data available for numbers. It will return nil in case there is no data or phone is impossible. Can return array of values in case there are some results for specified number

phone.geo_name # returns geo name of parsed phone
phone.timezone # returns timezone name of parsed phone
phone.carrier  # returns carrier name of parsed phone

Phone class has following attributes

phone.original        # string that was passed as phone number
phone.sanitized       # sanitized phone number (only digits left)

How it works

Gem includes data from Google libphonenumber which has regex patterns for validations. Valid patterns are more specific to phone type and country. Possible patterns as usual are patterns with number of digits in number.

Development and tests

Everyone can do whatever he wants, the only limit is your imagination. Just don't forget to write test before the pull request. In order to run test without Rails functionality simply use

bundle exec rake spec

If you want to run including Rails environment, you need to set BUNDLE_GEMFILE while running the spec task, for example:

BUNDLE_GEMFILE=gemfiles/Gemfile.rails-3.2.x bundle exec rake spec

Gemfiles can be found in gemfiles folder, there are gemfiles for Rails 3.1, 3.2, 4, 5 and 5.1.

phonelib's People

Contributors

bergey avatar chills42 avatar daddyz avatar dejanstrbac avatar dependabot[bot] avatar dm1try avatar dzunk avatar elmassimo avatar greysteil avatar hasclass avatar herbcso avatar huntrax11 avatar jkaipr avatar kaineer avatar mastahyeti avatar nicolasleger avatar olleolleolle avatar pbechu avatar pedromgsilva avatar petergoldstein avatar qmhoang avatar ryancheung avatar ryankepars avatar shanipribadi avatar sime avatar smudge avatar stevenvegt avatar styd avatar theycallmeswift avatar toxaq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phonelib's Issues

valid_for_country? returns false positives

Loading development environment (Rails 3.2.21)
[1] pry(main)> Phonelib.valid_for_country? '+591 3 3466166', 'DE'
=> true
[2] pry(main)> Phonelib.valid_for_country? '+55 11 2606-1011', 'DE'
=> true
[3] pry(main)> Phonelib.valid_for_country? '+7 926 398-00-95', 'DE'
=> true
[4] pry(main)> Phonelib.valid_for_country? '+55 1 5551234', 'AT'
=> true
[5] pry(main)> Phonelib.valid_for_country? '+57 1 2265858', 'DE'
=> true

I'm not sure of the extent of the problem, but a lot of numbers seem to be valid for Germany.

Fix gem name

This is an awesome gem but the name is a bit odd.. Phonelib the suffix lib is a bit weird especially for typical Ruby gems. Better to call it PhoneNumbers or something like that.

Handling numbers from Puerto Rico

Hey folks,

I noticed phonelib doesn't seem to treat numbers from Puerto Rico like it does for other US areas.

More specifically it does add a +1 to the e164 of a valid phone in most US area codes, but not for Puerto Rico's 787:

> Phonelib.parse("415 533 1234").e164
=> "+14155332319"

> Phonelib.parse("787 671 1234").e164
=> "+7876711234"

Default country is set to "US" in both cases.

Tried updating the data too, but still nothing.

Cannot parse int'l number without country code

Attempting to parse a valid international number fails if the number does not contain the correct country code - and there is no method exposed for retrieving the country code of a region.

Sample (number commented out for security, tested with a real Japanese number):

n = Phonelib.parse '+81 90 xxxx xxxx', 'JP'
n.valid_for_country?('JP') 
#=> true, number had country code

n = Phonelib.parse '90 xxxx xxxx', 'JP'
n.valid_for_country?('JP') 
#=> false, number did not have country code

area_code is not working

I pulled down the latest gem 0.6.2 but it is not working in 0.5.5 either. This is with my personal mobile but I'm getting same result with a different mobile as well.

[7] pry(main)> number = Phonelib.parse("+15306355653")
=> #<Phonelib::Phone:0x007f981a0ba6f8
@DaTa=
{"US"=>
{:id=>"US",
:country_code=>"1",
:international_prefix=>"011",
:main_country_for_code=>"true",
:national_prefix=>"1",
:national_prefix_optional_when_formatting=>"true",
:mobile_number_portable_region=>"true",
:national=>"5306355653",
:format=>{:pattern=>"(\d{3})(\d{3})(\d{4})", :format=>"($1) $2-$3", :intl_format=>"$1-$2-$3"},
:valid=>[:fixed_or_mobile],
:possible=>[:premium_rate, :toll_free, :personal_number, :fixed_or_mobile]}},
@extension="",
@national_number="5306355653",
@original="+15306355653",
@Sanitized="15306355653">
[8] pry(main)> number.possible?
=> true
[9] pry(main)> number.area_code
=> nil

Proper error required for malformed data

2.1.1 :001 > Phonelib.parse '0000','PH'
NoMethodError: undefined method `[]' for nil:NilClass
    from /usr/local/rvm/gems/ruby-2.1.1/gems/phonelib-0.3.0/lib/phonelib/phone_analyzer.rb:20:in `analyze'
    from /usr/local/rvm/gems/ruby-2.1.1/gems/phonelib-0.3.0/lib/phonelib/phone.rb:24:in `initialize'
    from /usr/local/rvm/gems/ruby-2.1.1/gems/phonelib-0.3.0/lib/phonelib/core.rb:108:in `new'
    from /usr/local/rvm/gems/ruby-2.1.1/gems/phonelib-0.3.0/lib/phonelib/core.rb:108:in `parse'
    from (irb):1
    from /usr/local/rvm/rubies/ruby-2.1.1/bin/irb:11:in `<main>'
2.1.1 :001 > Phonelib.parse '0000','IN'
NoMethodError: undefined method `[]' for nil:NilClass
    from /usr/local/rvm/gems/ruby-2.1.1/gems/phonelib-0.3.0/lib/phonelib/phone_analyzer.rb:20:in `analyze'
    from /usr/local/rvm/gems/ruby-2.1.1/gems/phonelib-0.3.0/lib/phonelib/phone.rb:24:in `initialize'
    from /usr/local/rvm/gems/ruby-2.1.1/gems/phonelib-0.3.0/lib/phonelib/core.rb:108:in `new'
    from /usr/local/rvm/gems/ruby-2.1.1/gems/phonelib-0.3.0/lib/phonelib/core.rb:108:in `parse'
    from (irb):1
    from /usr/local/rvm/rubies/ruby-2.1.1/bin/irb:11:in `<main>'

it's obvious my fault, but I think it should raise proper error. (not NoMethodError)

E164 numbers for some countries do not parse to the correct country

I have run into this issue specifically with New Zealand numbers, but it might affect other countries as well.

I can successfully parse landline NZ numbers such as +64 06 555 0123, which gives

[1] pry(main)> Phonelib.parse("+64 06 555 0123")
=> #<Phonelib::Phone:0x007f87b550dd60
 @data=
  {"NZ"=>
    {:id=>"NZ",
     :country_code=>"64",
     :international_prefix=>"0(?:0|161)",
     :preferred_international_prefix=>"00",
     :national_prefix=>"0",
     :national_prefix_formatting_rule=>"$NP$FG",
     :mobile_number_portable_region=>"true",
     :national=>"65550123",
     :format=>
      {:pattern=>"([34679])(\\d{3})(\\d{4})",
       :leading_digits=>"[346]|7[2-57-9]|9[1-9]",
       :format=>"$1-$2 $3"},
     :valid=>[:fixed_line],
     :possible=>[:toll_free, :pager, :fixed_or_mobile]}},
 @extension="",
 @national_number="65550123",
 @original="+64 06 555 0123",
 @sanitized="64065550123">
[2] pry(main)> Phonelib.parse("+64 06 555 0123").e164
=> "+6465550123"

However, if I then take that e164 formatted phone number and re-parse it, the output is incorrect:

[3] pry(main)> Phonelib.parse("+6465550123")
=> #<Phonelib::Phone:0x007f87b5bf4c50
 @data=
  {"US"=>
    {:id=>"US",
     :country_code=>"1",
     :international_prefix=>"011",
     :main_country_for_code=>"true",
     :national_prefix=>"1",
     :national_prefix_optional_when_formatting=>"true",
     :mobile_number_portable_region=>"true",
     :national=>"6465550123",
     :format=>
      {:pattern=>"(\\d{3})(\\d{3})(\\d{4})",
       :format=>"($1) $2-$3",
       :intl_format=>"$1-$2-$3"},
     :valid=>[:fixed_or_mobile],
     :possible=>[:premium_rate, :toll_free, :personal_number, :fixed_or_mobile]}},
 @extension="",
 @national_number="6465550123",
 @original="+6465550123",
 @sanitized="6465550123">

Phonelib thinks it's a US number, because 646 is a valid US area code for New York. As a work-around, I can replace the + with 00 when re-parsing to get the correct output, but that work-around breaks when trying to re-parse a US e164 number with a +1 at the beginning.

0.2.8 not parsing special characters

It looks like somewhere in between 0.2.6 and 0.2.8, Phonelib stopped parsing numbers with special characters. I skimmed the recent commits last night, but nothing stood out. I'll open a PR if I figure out what happened and can fix it.

(Thanks for the sweet gem, by the way.)

jennifer.brown@jbrown ~
$ cat parsing.rb
require 'phonelib'
require 'phonelib/version'

puts "Using #{Phonelib::VERSION}"
puts "Is #{'(202) 867-5309'} valid? #{Phonelib.parse('(202) 867-5309', 'US').valid?}"
puts "Is #{'2028675309'} valid? #{Phonelib.parse('2028675309', 'US').valid?}\n"

jennifer.brown@jbrown ~
$ ruby parsing.rb
Using 0.2.6
Is (202) 867-5309 valid? true
Is 2028675309 valid? true

jennifer.brown@jbrown ~
$ rvm use [email protected]
Using /Users/jennifer.brown/.rvm/gems/ruby-1.9.3-p448 with gemset phonelib-0.2.8

jennifer.brown@jbrown ~
$ ruby parsing.rb
Using 0.2.8
Is (202) 867-5309 valid? false
Is 2028675309 valid? true

No need to squeeze number from strange string

[1] pry(main)> Phonelib.valid_for_country?('*١١١*https://itunes.apple.com/us/app/no-name-for-twitter/id365306093?mt=8٤٤#', 'HU')
=> true
[2] pry(main)> Phonelib.parse('*١١١*https://itunes.apple.com/us/app/no-name-for-twitter/id365306093?mt=8٤٤#', 'HU')
=> #<Phonelib::Phone:0x00000005415e10
 @data=
  {"HU"=>
    {:id=>"HU",
     :country_code=>"36",
     :international_prefix=>"00",
     :national_prefix=>"06",
     :national_prefix_formatting_rule=>"($FG)",
     :mobile_number_portable_region=>"true",
     :national=>"53060938",
     :format=>
      {:pattern=>"(\\d{2})(\\d{3})(\\d{3,4})",
       :leading_digits=>"[2-9]",
       :format=>"$1 $2 $3"},
     :valid=>[:fixed_line],
     :possible=>[:premium_rate, :toll_free, :shared_cost, :fixed_line]}},
 @national_number="53060938",
 @original=
  "*١١١*https://itunes.apple.com/us/app/no-name-for-twitter/id365306093?mt=8٤٤#">
*١١١*https://itunes.apple.com/us/app/no-name-for-twitter/id365306093?mt=8٤٤#
----------------------------------------------------------vvvvvvvvvv---v-----

It's weird...

Active Record Integration seems to be buggy

When using the active record integration to check whether a provided number is a valid mobile number using

validates :phone, uniqueness: true, presence: true, phone: { possible: true, allow_blank: true, types: [ :mobile ] } and then using a more exotic phone number such as 639297912345 the corresponding record cannot be saved.

However, if I validate it myself using

validates_uniqueness_of :phone
validate :valid_phone
def valid_phone
    p = Phonelib.parse(self.phone)
    phone_valid = p && p.valid? && p.types.include?(:mobile)
    errors.add(:phone, 'phone number seems to be invalid') if !phone_valid  
  end

The record can be saved.

Canadian mobile numbers detected as fixed_line

I'm using phonelib 0.4.8, parsing phone numbers and allowing only mobile and fixed_or_mobile types
as our app sends SMS we don't need to allow users to register with a land line,

When We parse mobile numbers for Canadian operator Tulsa '+1514659xxx2' we get the type as fixed_line and we expected the library to return mobile number, even if there is a doubt a fixed_or_mobile could be allowed.

so am i getting this right and this is a bug or there is something I'm missing in my code?

Cannot parse Algeria mobile phone number

Hi, are you sure this gem include all the countries, currently trying to parse an Algerian mobile number (country ISO code is DZ), it does not parse:

[10] pry(main)> phone = Phonelib.parse("0612345678", "DZ")
=> #<Phonelib::Phone:0x007fd8ae414680 @data={}, @national_number="0612345678", @original="0612345678">

Thanks.

Not work in Rails 4

It would raise Unknown validator: 'PhoneValidator' (ArgumentError) in Rails 4

Different results for parsed variations

The following 4 lines should produce the same results, yet they do not:

Phonelib.parse('478-714-7999','US').valid?

(returns true)

Phonelib.valid_for_country?('478-714-7999', 'US')

(returns true)

Phonelib.parse('478-714-7999','US').valid_for_country?('US')

(returns true)

Phonelib.parse('478-714-7999').valid_for_country?('US')

(returns false)

CN =

But it should be since 0 is a standard prefix in China's fixed line system.

validates phone: true affects shoulda-matcher test

When i include the following tests:
validates_presence_of :phone_number
validates :phone_number, phone: true

this test
it { should validate_presence_of :phone_number }

will fail with the following error
NoMethodError:
undefined method `gsub' for nil:NilClass

but without the phone: true, this error isn't thrown. Is there something affecting shoulda-matcher? Is there something I should be aware of in terms of running rspec tests?

Parsing and using e.164 phone number with extensions

I haven't found much on extensions, but this writeup on best practices suggests the following e.164 format for phones with extensions:

+19052223333;ext=555

Unfortunately, here's what I get:

phone = Phonelib.parse('+19052223333;ext=555')
phone.valid? # false
phone.e164  # +19052223333555

We need to support extensions and would like to store everything in a normalized e.164 format (not separate columns), is there an option to get this to parse properly?

E164 formatter regression

Phonelib.parse('1').e164 will throw an error: TypeError: no implicit conversion of nil into String. Appeared in version 0.6.1.

Regression in country detection: leading digits

I just upgraded from 0.4.5 to 0.4.9 and noticed a regression (it seems):
Taken this basic number that used to be detected correctly as a US number: +17295470713
It now says the country code is "AG", whereas this is just a small zone with numbers starting by "1-268".
So it seems to now take the first country matching the international prefix ("1") without taking care of the leading digits ("268" is NOT matching in this case).

Phonelib.parse('+17295470713').country # => "AG"

I've temporarily rollbacked to 0.4.5

Mexico numbers are not being parse correctly.

I have a mobile phone number for example: '15547898478' | '+5215547898478'

number = Phonelib.parse('+5215545258448', 'mx')
number.international => "+52 044 55 4525 8448"
number.national => "044 55 4525 8448"

# is number.international valid for mexico?
Phonelib.valid_for_country?(number.international, 'mx')  => false

"+52 044 55 4525 8448" is not a valid phone number, for the international number the number should stay the same with the additional (+)country_code.

number = Phonelib.parse('+5215545258448', 'mx')
number.international => "+52 1 55 4525 8448"
number.national => "044 55 4525 8448"

# is number.international valid for mexico?
Phonelib.valid_for_country?(number.international, 'mx')  => true

I've only tested numbers for Mexico but maybe is the same issue with numbers that adds a prefix like in this case "044" to the original number.

Thanks for your help.

E164 formatted number parsed differently when a country is passed

When I'm passing a properly formatted international number with a different country, it isn't handled correctly.

The following snip demonstrates the issue, I would expect the result to be the same.

require 'phonelib'
p Phonelib.parse('+4920180912345')
p Phonelib.parse('+4920180912345', 'US')

Clarification for US phone number validations

We are using phonelib (0.4.9) in our rails project.
Phone number validation is performed using following function call:

Phonelib.valid_for_country?([phone_number], [apha2_country_code]).

Our web site mostly is USA-oriented thus major phone number validations are validated for 'US' country code.
And we are noticed, that phone numbers like with length from 5-9 digits (like 12345, 123456, etc ) are passing validation for US country code.

Here us console raw testing results
Loading development environment (Rails 3.2.12)
2.1.2 :001 > Phonelib.valid_for_country? '12345', 'US'
=> true
2.1.2 :002 > Phonelib.valid_for_country? '123456', 'US'
=> true
2.1.2 :003 > Phonelib.valid_for_country? '1234567', 'US'
=> true

Is it correct behaviour of this library because as far as I know it should be at least 10 digit for USA?
If I'm missing some setting, please correct me.

International prefix duplicated

When I parse these numbers, the international prefix (49) gets duplicated:

Phonelib.parse("+49157123456789", "de").international
=> "+49 491 57123456789"

pry(main)> Phonelib.parse("+49157123456789", "de").valid?
=> true

Phonelib.parse("+491521234567", "de").international
=> "+49 491 521234567"

Phonelib.parse("+491521234567", "de").valid?
=> true

Both numbers should be invalid (the first subscriber number is too long, the second too short). But they are both detected as valid. IMO, even if the number is invalid, the international prefix shouldn't be duplicated.

Crash with some phone numbers

I got some trouble when initializing some phone numbers like this 119660086441:

phone = Phonelib::Phone.new("119660086441")
NoMethodError: undefined method `match' for nil:NilClass
~/.rvm/gems/ruby-2.0.0-p643/gems/phonelib-0.4.7/lib/phonelib/phone_analyzer.rb:211:in `block in get_number_format'
~/.rvm/gems/ruby-2.0.0-p643/gems/phonelib-0.4.7/lib/phonelib/phone_analyzer.rb:209:in `each'
~/.rvm/gems/ruby-2.0.0-p643/gems/phonelib-0.4.7/lib/phonelib/phone_analyzer.rb:209:in `find'
~/.rvm/gems/ruby-2.0.0-p643/gems/phonelib-0.4.7/lib/phonelib/phone_analyzer.rb:209:in `get_number_format'
~/.rvm/gems/ruby-2.0.0-p643/gems/phonelib-0.4.7/lib/phonelib/phone_analyzer.rb:149:in `get_national_and_data'
~/.rvm/gems/ruby-2.0.0-p643/gems/phonelib-0.4.7/lib/phonelib/phone_analyzer.rb:69:in `parse_single_country'
~/.rvm/gems/ruby-2.0.0-p643/gems/phonelib-0.4.7/lib/phonelib/phone_analyzer.rb:81:in `block in detect_and_parse'
~/.rvm/gems/ruby-2.0.0-p643/gems/phonelib-0.4.7/lib/phonelib/phone_analyzer.rb:80:in `each'
~/.rvm/gems/ruby-2.0.0-p643/gems/phonelib-0.4.7/lib/phonelib/phone_analyzer.rb:80:in `detect_and_parse'
~/.rvm/gems/ruby-2.0.0-p643/gems/phonelib-0.4.7/lib/phonelib/phone_analyzer.rb:26:in `analyze'
~/.rvm/gems/ruby-2.0.0-p643/gems/phonelib-0.4.7/lib/phonelib/phone.rb:24:in `initialize'

Exceptions raised for certain phone numbers

I found some phone numbers which raise an exception for the #national and #international methods. These numbers pass the #valid? test for the country, but none of the more specific formats for the country match the number.

Here are a few examples:

Phonelib.parse('54932', 'DE').national
Phonelib.parse('33251304029', 'LU').national
Phonelib.parse('61130374', 'AU').national

Canadian Area Codes

Some Canadian area codes don't result with a correctly formatted number. Two examples are area codes are 306 and 416. To test or recreate the issue, you can use 3065555555 or 4165555555. Neither results in valid formatted phone numbers.

These are valid area codes. Our code to create the formatted number:

def clean_up_number
phone = Phonelib.parse(number)
return false if phone.blank?
self.number = phone.extension.present? ? "#{phone.e164};#{phone.extension}" : phone.e164
self.country_code = phone.country_code
true
end

Any suggestion would be greatly appreciated. (We're using v 0.5.2, Rails 4.1.10)

It doesn't auto-detect country code from the passed phone number

The latest version, v0.2.3, don't auto-detect country code any more. I try the code bellow:

[3] pry(main)> phone = Phonelib.parse("+41 44 668 18 00");
[4] pry(main)> phone.valid?
=> false

But it works in the version v0.1.3, which I'm using at the moment.

Invalid number for Colombia

Hi,

I have a case of an invalid number for Colombia +573234827533, I'm using the following:

2.1.1 :008 > number = Phonelib.valid?('+573234827533') => false

The number +573234827533 is a valid phone number for Claro Colombia, can you please check why the validation fails.

Here is an example of a number that passes the phonelib validation:

2.1.1 :007 > number = Phonelib.valid?('+573202605272') => true

Note: I'm using phonelib 0.6.2

Thanks.

National number with extension

I saw that in #64 the methods full_international and full_e164 were added. Should a full_national also be included in order to get a formatted national number with extension?

Robustifying input protection

Hi, thanks for this gem. I'm just transitioning from the abandoned global_phone gem and one of my tests fails as I was throwing it an intentionally invalid number which happened to be an integer

Phonelib.parse(123456789)
 NoMethodError: undefined method `split' for 123456789:Fixnum

 Phonelib.parse('123456789')
 => #<Phonelib::Phone:0x007f84e7899360 ....

Might be worth, in the interest of input protection, to convert original to a string when passing it to split_extensions? ie in Phonelib::Phone

def initialize(original, country = nil)
  @original, @extension = separate_extension(original.to_s) # Add 'to_s' here

Would submit a pull request but it may not be wanted, as it's not absolutely necessary, and is only a four character change.

Number Valid checker returns true for alphanumeric string

Take a local US Number as a string
and append and prepend a alphabets to the string
just replace the xxx with a number which you know
For eg:
num_string = 'asfas+1xxxxxxxxxxfsafsffsafa'
Phonelib.valid? num_string
It returns true
But actually it should return false right?

#normalize implementation

Related to extension parsing #58, I would like to have a consistent way to store numbers in the database. One that hopefully is standard but unlikely to change.

I was using #e164, but with the addition of #58 extensions, the #e164 doesn't include the extension for storage.

@daddyz are you interested in a Phonelib.normalize as a pull request? This is working for me, renders extensions with the ;

Something like

    def normalize(phone_number)
      phone = ::Phonelib.parse(phone_number)
      value = phone.e164
      value = "#{value};#{phone.extension}" unless phone.extension.blank?
      value
    end

Parsing German Five-digit area codes

phone_number = Phonelib.parse('+4902304973401', 'DE')
phone_number.national # => "023 04973401" 

But the correct national formatting according to http://libphonenumber.appspot.com/phonenumberparser would be "02304 973401", 02304 being the prefix for Schwerte in North Rhine-Westphalia.

I found that in get_number_format way too many formats match because the ^-operator only applies to the first term of the Regexp (so leading_digits "3[02]|40|[68]9" is incorrectly matching).

I can create a pull request if you like.

Getting the national number without the country code or formatting

I have a phone number, from which I want he unformatted national number, without the country code. This is the phone number:

 2.2.1 :001 > phone = Phonelib.parse('16469129444')
 => #<Phonelib::Phone:0x007fef7814f590 @original="16469129444", @extension="", @sanitized="16469129444", @data={"US"=>{:id=>"US", :country_code=>"1", :international_prefix=>"011", :main_country_for_code=>"true", :national_prefix=>"1", :national_prefix_optional_when_formatting=>"true", :mobile_number_portable_region=>"true", :national=>"6469129444", :format=>{:pattern=>"(\\d{3})(\\d{3})(\\d{4})", :format=>"($1) $2-$3", :intl_format=>"$1-$2-$3"}, :valid=>[:fixed_or_mobile], :possible=>[:premium_rate, :toll_free, :personal_number, :fixed_or_mobile]}}, @national_number="6469129444">

I'm looking to get the '@national_number', but can't since there's no getter for that. Any ideas? Now I do this, which is not optimal:

phone.e164.sub('+1', '')

Wrong international number format for Lithuanian numbers

In lithuania you may have ever 8 or 370
so national code is 8, international code 370

Phonelib.parse('370 611 11 111').countries
=> ["LT"]
Phonelib.parse('00370 611 11 111').countries
=> ["CN"]

Phonelib.parse('370 611 11 111').international
=> "+370 (8-611) 11111"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.