Giter Site home page Giter Site logo

telephone_number's Introduction

Build Status Code Climate Coverage Status

What is it?

TelephoneNumber is global phone number validation gem based on Google's libphonenumber library.

Demo

Feel free to check out our demo!

Numberjack

Installation

Add this line to your application's Gemfile:

gem 'telephone_number'

And then execute:

$ bundle

Or install it yourself as:

$ gem install telephone_number

Supported Ruby Versions

This library requires Ruby 2.4 or later.

Rails Validation

validates :my_attribute_name, telephone_number: {country: proc{|record| record.country}, types: [:fixed_line, :mobile, etc]}

Valid Phone Types

  • :area_code_optional
  • :fixed_line
  • :mobile
  • :no_international_dialling
  • :pager
  • :personal_number
  • :premium_rate
  • :shared_cost
  • :toll_free
  • :uan
  • :voicemail
  • :voip

Country

  • In this example, record.country must yield a valid two letter country code such as :us, :ca or 'DE'
  • You can also just pass a String or Symbol instead of a Proc.

Manual Usage

You can obtain a TelephoneNumber object by calling:

phone_object = TelephoneNumber.parse("3175082237", :us) ==>

#<TelephoneNumber::Number:0x007fe3bc146cf0
  @country=:US,
  @e164_number="13175083348",
  @national_number="3175083348",
  @original_number="3175083348">

After that you have the following instance methods available to you.

  • valid_types

    Returns all types that the number is considered valid for.

    phone_object.valid_types ==> [:fixed_line, :mobile, :toll_free]

  • valid?

    Returns boolean value indicating whether or not valid_types is empty.

    phone_object.valid? ==> true

  • national_number(formatted: true)

    Returns the national formatted number including special characters such as parenthesis and dashes. You can omit the special characters by passing formatted: false

    phone_object.national_number ==> "(317) 508-2237"

  • international_number(formatted: true)

    Returns the international formatted number including special characters such as parenthesis and dashes. You can omit the special characters by passing formatted: false

    phone_object.international_number ==> "+1 317-508-2237"

  • e164_number(formatted: true)

    Returns the international formatted number including special characters such as parenthesis and dashes. You can omit the special characters by passing formatted: false

    phone_object.e164_number ==> "+13175082237"

  • country

    Returns an object containing data related a the number's country.

    phone_object.country ===>
     #<TelephoneNumber::Country:0x007fb976267410
     @country_code="1",
     @country_id="US",
     ...
    
  • location

    Returns the location of the number. Default locale is :en

    phone_object.location ==> "Indiana"

    phone_object.location(:ja) ==> "ソウル特別市"

  • timezone

    Returns the time zone of the number.

    phone_object.timezone ==> "America/New_York"

Class Methods

You also have the following class methods available to you.

  • parse

    Returns a TelephoneNumber object.

    TelephoneNumber.parse("3175082237", :US)

    If you pass an E164 formatted number, we will determine the country on the fly.

    TelephoneNumber.parse("+13175082237")

  • valid?

    Returns boolean value indicating whether or not a particular number is valid.

    TelephoneNumber.valid?("3175082237", :US) ==> true

    If you are looking to validate against a specific set of keys, you can pass in an array of keys

    TelephoneNumber.valid?("3175082237", :US, [:mobile, :fixed_line]) ==> true
    TelephoneNumber.valid?("3175082237", :US, [:toll_free]) ==> false
    
  • invalid?

    Returns boolean value indicating whether or not a particular number is invalid.

    TelephoneNumber.invalid?("3175082237", :US) ==> false

    If you are looking to invalidate against a specific set of keys, you can pass in an array of keys

    TelephoneNumber.invalid?("3175082237", :US, [:mobile, :fixed_line]) ==> false
    TelephoneNumber.invalid?("3175082237", :US, [:toll_free]) ==> true
    

Configuration

Override File

In the event that you need to override the data that Google is providing, you can do so by setting an override file. This file is expected to be in the same format as Google's as well as serialized using Marshal.

To generate a serialized override file:

ruby bin/console
TelephoneNumber.generate_override_file("/path/to/file")

In this instance, /path/to/file represents an xml file that has your custom data in the same structure that Google's data is in.

You can set the override file with:

TelephoneNumber.override_file = "/path/to_file.dat"

Default Number Pattern

If TelephoneNumber is passed an invalid number and then asked to format that number, it will simply return an unformatted string of the originally passed number. This is because formatting rules will not be found for invalid numbers. If this is unacceptable, you can set a default_format_pattern and default_format_string that TelephoneNumber will use attempt to format invalid numbers.

TelephoneNumber.default_format_pattern = "(\\d{3})(\\d{3})(\\d*)"
TelephoneNumber.default_format_string = "($1) $2-$3"

invalid_number = "1111111111"
phone_object = TelephoneNumber.parse(invalid_number, :US)
phone_object.national_number ==> "(111) 111-1111"

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

While developing new functionality, you may want to test against specific phone numbers. In order to do this, add the number to lib/telephone_number/test_data_generator.rb and then run rake data:test:import. This command will reach out to the demo application provided by Google and pull the correct formats to test against.

To install this gem onto your local machine, run bundle exec rake install.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/mobi/telephone_number. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

telephone_number's People

Contributors

akfernun avatar ankita-ac avatar atavistock avatar chelseaworrel avatar iguchi1124 avatar j3ck avatar jaredpavan avatar jaykravetz avatar joshwetzel avatar olleolleolle avatar parvesh-tangoe avatar trouta23 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

telephone_number's Issues

CHANGELOG.md file missing

Hi

I find that the releases tag shows which versions exists but I can't find a place to show what changed when, so I can know why I should update or not.

Having a file CHANGELOG.md is a good way or putting the changes on relases/ on github is another one.

What do you think?

e164 formatted number contains duplicate country code

Gem Version: 1.4.9 and 1.4.11
Ruby Version: 2.6.6

Example (last 4 digits anonymized):

irb(main):006:0> TelephoneNumber.parse('+4917880xxxx').e164_number
=> "+494917880"

You can see that the input number starts with 49, but the e164 number starts with 4949.

Country instance methods missing

given phone_object = TelephoneNumber.parse("3175082237", :us),

phone_object.country #=> NoMethodError
phone_object.country_data #=> NoMethodError

The data is still accessible but must be called via:

phone_object.phone_data.country_data[:id] #=> "US"
phone_object.phone_data.country_data #=> {Hash}

Could you please update either the code or the documentation?

Phone number from foreign country not understood correctly

I'm expecting a well-formed foreign number, even if there is a country bias, to be understood correctly. For instance, if I dial +41446681800 in Canada, I need to understand that this is a valid Swiss number (+41).

n = TelephoneNumber.parse("+41446681800", :ca)

n.valid? 
# false
# Expected: true

n.country.country_id
# "CA"
# Expected: "CH"

n.e164_number
# "41446681800"
# Expected: "+41446681800"

Phone number showing valid even if it's invalid

I have installed gem in ruby on rails project, its' showing +91 1231 231 1 as valid number but it's not a valid number.

Example:

TelephoneNumber.parse('+91 1231 231 1').valid? # coming true
TelephoneNumber.valid?('+91 1231 231 1') # coming true
TelephoneNumber.valid?('+91 1231 231 1', :IN) # coming true

I have tried in demo website http://numberjack.io/ it's showing invalid to this above number.

Phone invalid when using [:mobile] without country code. And validator auto detect?

irb(main):022> TelephoneNumber.valid?('+85290191054')
=> true
irb(main):023> TelephoneNumber.valid?('+85290191054', [:mobile])
=> false
irb(main):024> TelephoneNumber.valid?('+85290191054', 'HK', [:mobile])
=> true

Is this by design? 🤔

My scenario:

  • User types phone number in 1 field (no country selector), manually, including their prefix
  • I want to auto-detect the country, and then also validate it

So, I'm using the validator like so:

validates :mobile_number, telephone_number: { country: proc { |record| TelephoneNumber.parse(record.mobile_number).country&.country_id }, types: [:mobile] }

This works fine, but would it be possible to auto-detect like i do here, but without specifying the country option, or another attribute like detect_country: true?

Thanks :)

not working for Indian mobile number

Hello, tried parsing the complete indian mobile number along with country code, but he object's location method returns nothing.

Please let me know, if I am missing something

this returns nothing, only empty line

require 'telephone_number'
mobile = TelephoneNumber.parse("+917503907302")
puts mobile.location

Typo in doc about timezone

timezone
Returns the time zone of the number.

phone_object.location ==> "America/New_York"

location in place of timezone

Hi.

Do you have any script for Ruby Programming like this:

Enter username facebook or url facebook of person: etc

FULL NAME: JOHN DOE
PHONE NUMBER: 200202022
LAT.
LONG.....

Im getting is valid even if the phone contains weird chars

Hi

I am doing something wrong?

Im trying to validate a phone number and it always says that it is valid but to me it should say that it is not:

irb(main):016:0> TelephoneNumber.valid?("+573053036788-qwdqwdqwd-qwdqwd-asd")
=> true
irb(main):017:0> TelephoneNumber.valid?("+573053036788-qwdqwdqwd-qwdqwd-as(d")
=> true
irb(main):018:0> TelephoneNumber.valid?("+573053036788-qwdqwdqwd-)qwdqwd-as(d")
=> true

Namespace - TelephoneNumber is too common

I would love to use this gem as it seems to solve issue both Phony and GlobalPhone have, but ...

We already have a class named TelephoneNumber in our application, that coincidentally is a telephone number

Using the constant TelephoneNumber, without any namespacing, is likely to not only clash with our application, but with others too

On a more philosophical level, you are using a constant that is a noun as opposed to a name that represents a library for number parsing/formatting

Any chance this can be namespaced without us having to fork and namespace it ourselves? (which will make updates impossibly hard)

Gem does not support the numbers from Sri Lanka and Vietnam

Could you add please the numbers from Sri Lanka and Vietnam? Because at the moment it seems to not work.

Example:
pry(main)> TelephoneNumber.parse("+84283456789").valid? => false
pry(main)> TelephoneNumber.parse("+84283456789").country.country_id NoMethodError: undefined method 'country_id' for nil:NilClass

Support for multiple countries?

We have users who try to use our app who have virgin islands phone numbers or canadian phone numbers... We currently validate against US, but it would be nice to be able too validate against any number with a +1 country code

invalid number that is valid

TelephoneNumber.parse('+543801234567', :ar).valid?
=> false

Tested with version 1.4.9 and 1.4.8

Numberjacki.io says this is a valid number..

Phone Parser bad result

When use TelephoneNumber.parse("621791146") the phone number is identified as an Indonesian number by default
But in this case, it's a Luxembourg number
Here, it confuses the Indonesian country code with a number base valid in 62 Luxembourg.

TelephoneNumber.parse("621791146")
#<TelephoneNumber::Number:0x00005555837144f8 @original_number="621791146", @country=#<TelephoneNumber::Country:0x00005555842b8ef8 @country_code="62", @country_id="ID", ...
TelephoneNumber.parse("621791146").e164_number
# "+62621791146"

TelephoneNumber.parse("621791146", :LU).e164_number
# "+352621791146"

Receiving NameError when trying to use valid?

Ruby version: ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin16]
OS: OSX

Here's the stack trace of the error I'm seeing:

NameError: uninitialized constant TelephoneNumber::Number::Forwardable
	from /Users/jared.pavan/.rvm/gems/ruby-2.3.1/gems/telephone_number-1.2.0/lib/telephone_number/number.rb:3:in `<class:Number>'
	from /Users/jared.pavan/.rvm/gems/ruby-2.3.1/gems/telephone_number-1.2.0/lib/telephone_number/number.rb:2:in `<module:TelephoneNumber>'
	from /Users/jared.pavan/.rvm/gems/ruby-2.3.1/gems/telephone_number-1.2.0/lib/telephone_number/number.rb:1:in `<top (required)>'
	from /Users/jared.pavan/.rvm/rubies/ruby-2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
	from /Users/jared.pavan/.rvm/rubies/ruby-2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
	from /Users/jared.pavan/.rvm/gems/ruby-2.3.1/gems/telephone_number-1.2.0/lib/telephone_number/class_methods.rb:11:in `parse'
	from /Users/jared.pavan/.rvm/gems/ruby-2.3.1/gems/telephone_number-1.2.0/lib/telephone_number/class_methods.rb:15:in `valid?'
	from (irb):2
	from /Users/jared.pavan/.rvm/rubies/ruby-2.3.1/bin/irb:11:in `<main>'```

Giving invalid validation for following numbers

23776671338

Country Code ---- 237
Country --- Cameroon
TelephoneNumber.invalid?('76671338', 'CM', [:mobile, :fixed_line])
giving true for this

559282828685
Country Code -- 55
Country -- BR
TelephoneNumber.invalid?('9282828685', 'BR', [:mobile, :fixed_line])

But these two numbers i have received from whatsapp meta webhook

[{"id"=>"102901402735930", "changes"=>[{"value"=>{"messaging_product"=>"whatsapp", "metadata"=>{"display_phone_number"=>"918069195810", "phone_number_id"=>"109626598719981"}, "contacts"=>[{"profile"=>{"name"=>"A. Banderas"}, "wa_id"=>"23776671338"}], "messages"=>[{"context"=>{"from"=>"918069195810", "id"=>"wamid.HBgLMjM3NzY2NzEzMzgVAgARGBI0NDNDNTk2QjI3RDk5MDc2RTAA"}, "from"=>"23776671338", "id"=>"wamid.HBgLMjM3NzY2NzEzMzgVAgASGBQzQUQ3QkU0NTg2RDQ1QTZDNERERQA=", "timestamp"=>"1681753310", "type"=>"interactive", "interactive"=>{"type"=>"list_reply", "list_reply"=>{"id"=>"2", "title"=>"CNSGH To CMDLA", "description"=>"Shanghai (CNSGH), Shanghai, Ch.. To Douala (CMDLA), Douala, Cameroon"}}}]}, "field"=>"messages"}]}]

[{"id"=>"102901402735930", "changes"=>[{"value"=>{"messaging_product"=>"whatsapp", "metadata"=>{"display_phone_number"=>"918069195810", "phone_number_id"=>"109626598719981"}, "contacts"=>[{"profile"=>{"name"=>"Daniella Martins"}, "wa_id"=>"559282828685"}], "messages"=>[{"context"=>{"from"=>"918069195810", "id"=>"wamid.HBgMNTU5MjgyODI4Njg1FQIAERgSRTVBMTU1MzQyRjI1OTJFNkZCAA=="}, "from"=>"559282828685", "id"=>"wamid.HBgMNTU5MjgyODI4Njg1FQIAEhgUM0FCN0QzNUNCQ0E1NTk3NDEzQTEA", "timestamp"=>"1681183686", "type"=>"interactive", "interactive"=>{"type"=>"button_reply", "button_reply"=>{"id"=>"1", "title"=>"Make a new search"}}}]}, "field"=>"messages"}]}]

If these two are verified from whatsapp , so i should also be able to save these numbers in my database, but the gem gives invalid for both

Giving invalid validation for following US number

I am trying the following code, but it is returning invalid for me, 945 is a recently area code added to Dallas, do we have any prevision about when it will be added to this gem?

 TelephoneNumber.parse('9452642426').valid?
=> false

How to run and csv upload

Hello i m new at this and ruby , please can you explain how to run? after gem install telephone_number what should i do to run?
And how can i make csv upload and get generated csv ? Thnx

Discrepancy between libphonenumber and mobi / telephone_number

Hi,
We are working with Australia, and inside libphonenumber (libphonenumber.appspot.com) we see that this australian number is mobile - 0460 441 216
While on your demo is seems to be invalid
This is causing our product to not support these numbers

undefined method `match?'

Hi,

After the update to 1.4.0, I'm getting this error:

NoMethodError: undefined method match?' for "11986865178":String Did you mean? match from telephone_number/parser.rb:34:in block in validate'
from telephone_number/parser.rb:33:in select' from telephone_number/parser.rb:33:in validate'
from telephone_number/parser.rb:12:in valid_types' from telephone_number/parser.rb:16:in valid?'
from forwardable.rb:202:in valid?' from telephone_number/formatter.rb:9:in initialize'
from telephone_number/number.rb:14:in new' from telephone_number/number.rb:14:in initialize'
from telephone_number/class_methods.rb:11:in new' from telephone_number/class_methods.rb:11:in parse'
from telephone_number/class_methods.rb:15:in valid?' from telephone_number/class_methods.rb:19:in invalid?'
from active_model/telephone_number_validator.rb:5:in validate_each' from active_model/validator.rb:167:in block in validate'
from active_model/validator.rb:164:in each' from active_model/validator.rb:164:in validate'

Regards,

Version 1.4.17 seems to have disappeared

Our lockfile includes 1.4.17, but today I was no longer able to bundle. Took a look at Rubygems and saw the jump from .16 to .18, so also checked the CHANGELOG and see the same thing. Did something happen? Any information would be appreciated, mostly so we know if there's something to worry about.

Is it possible to get a user-friendly format string suitable for displaying to the user?

The validations in this gem are great! I'm wondering if it's possible to get a user-friendly format string out somehow that is suitable for displaying to end users, in a form input placeholder or hint, for example? That would really make it shine.

Example for the US (United States):
"(xxx) xxx-xxxx"

Something like that would be awesome, because then we could pipe it into a client-side Javascript library to validate the format on the client-side as well, and give the user hints about the acceptable format for their country.

Thanks for a great gem!

Error messages for validation failure

Hi,

The isValid method simply returns a boolean without an error message regarding the failure cause. Is there anyway we can hook into the validation message as it will be helpful to the end user?

Regards,

Deepak

How Get National Area Code

How can I get the national code of a phone and just the number without the national code?

irb(main):064> result = TelephoneNumber.parse("+5555999999999")
=>
#<TelephoneNumber::Number:0x000000013d4d5d30
...
irb(main):065> result.international_number
=> "+55 55 99999-9999"
irb(main):066> result.national_number
=> "(55) 99999-9999"
irb(main):067> result.national_area_code
(irb):67:in `<main>': undefined method `national_area_code' for an instance of TelephoneNumber::Number (NoMethodError)

ArgumentError (Unknown validator: 'TypesValidator')

No sure what i'm doing wrong but seeing:

ArgumentError (Unknown validator: 'TypesValidator')

with the following line:

validates :phone, telephone_number: :us, types: [:fixed_line, :mobile]

Version: telephone_number (1.3.1)

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.