Giter Club home page Giter Club logo

globalphone's Introduction

GlobalPhone Build Status Build status

GlobalPhone parses, validates, and formats local and international phone numbers according to the E.164 standard.

Store and display phone numbers in your app. Accept phone number input in national or international format. Convert phone numbers to international strings (+13125551212) for storage and retrieval. Present numbers in national format ((312) 555-1212) in your UI.

Designed with the future in mind. GlobalPhone uses the c# implementation based on Google's open-source libphonenumber database.

Installation

  1. Add the GlobalPhone nuget package to your app. For example, using Package Manager Console:

     PM> Install-Package GlobalPhone
    

Or you can add it as a solution level package.

Examples

Parse an international number string into a GlobalPhone::Number object:

var number = GlobalPhone.Parse("+1-312-555-1212");
# => #{GlobalPhone::Number +13125551212}

Query the country code and likely territory name of the number:

number.CountryCode
# => 1

number.RegionCode
# => "US"

Present the number in national and international formats:

number.NationalFormat
# => "(312) 555-1212"

number.InternationalFormat
# => "+1 312-555-1212"

Is the number valid? (Note: this is not definitive. For example, the number here is "IsValid" by format, but there are no US numbers that start with 555. The IsValid method may return false positives, but should not return false negatives unless the database is out of date.)

number.IsValid
# => true

Get the number's normalized E.164 international string:

number.InternationalString
# => "+13125551212"

Parse a number in national format for a given territory:

number = GlobalPhone.Parse("(0) 20-7031-3000", "gb");
# => #{GlobalPhone::Number +442070313000}

Parse an international number using a territory's international dialing prefix:

number = GlobalPhone.Parse("00 1 3125551212", "gb");
# => #{GlobalPhone::Number +13125551212}

Set the default territory to Great Britain (territory names are ISO 3166-1 Alpha-2 codes):

GlobalPhone.DefaultTerritoryName = "gb";
# => "gb"

GlobalPhone.Parse("(0) 20-7031-3000");
# => #{GlobalPhone::Number +442070313000}

Shortcuts for validating a phone number:

GlobalPhone.Validate("+1 312-555-1212");
# => true

GlobalPhone.Validate("+442070313000");
# => true

GlobalPhone.Validate("(0) 20-7031-3000");
# => false

GlobalPhone.Validate("(0) 20-7031-3000", "gb");
# => true

Shortcuts for normalizing a phone number in E.164 format:

GlobalPhone.Normalize("(312) 555-1212");
# => "+13125551212"

GlobalPhone.Normalize("+442070313000");
# => "+442070313000"

string normalized;
GlobalPhone.TryNormalize("(0) 20-7031-3000", out normalized);
# => false

GlobalPhone.Normalize("(0) 20-7031-3000");
# => #{PhoneNumbers::NumberParseException}

GlobalPhone.Normalize("(0) 20-7031-3000", "gb");
# => "+442070313000"

Caveats

GlobalPhone currently does not parse emergency numbers or SMS short code numbers.

Validation is not definitive and may return false positives, but should not return false negatives unless the database is out of date.

Territory heuristics are imprecise. Parsing a number will usually result in the territory being set to the primary territory of the region. For example, Canadian numbers will be parsed with a territory of US. (In most cases this does not matter, but if your application needs to perform geolocation using phone numbers, GlobalPhone may not be a good fit.)

Development

The GlobalPhone source code is hosted on GitHub. You can check out a copy of the latest code using Git:

CMD> git clone https://github.com/GlobalPhone/GlobalPhone.git

If you've found a bug or have a question, please open an issue on the issue tracker. Or, clone the GlobalPhone repository, write a failing test case, fix the bug, and submit a pull request.

GlobalPhone is a port of Sam Stephenson GlobalPhone for ruby hosted on GitHub.

License

Copyright © 2013 Sam Stephenson, Oskar Gewalli

Released under the MIT license. See LICENSE for details.

globalphone's People

Contributors

agoretsky avatar dependabot[bot] avatar wallymathieu avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

globalphone's Issues

DatabaseGenerator is concatenating leadingDigits collection from XML source into one pattern string

Perhaps I can start with an example: the GB mobile phone number 07400 123456. If we put that into the libphonenumber online tool (https://rawgit.com/googlei18n/libphonenumber/master/javascript/i18n/phonenumbers/demo-compiled.html), then it returns the formatted national string "07400 123456" (as expected).

If I try to parse that number using GlobalPhone.Parse("07400 123456", "GB"), it returns "074 0012 3456" as the formatted national string, which looks incorrect (note the spacing).

I had a bit of a debug and it seems that the correct format for displaying this number is not being chosen. In the source XML from libphonenumber, the corresponding XML fragment for this case is:

    <numberFormat pattern="(7\d{3})(\d{6})">
      <leadingDigits>
        7(?:
          [1-5789]|
          62
        )
      </leadingDigits>
      <leadingDigits>
        7(?:
          [1-5789]|
          624
        )
      </leadingDigits>
      <format>$1 $2</format>
    </numberFormat>

That is, there are two leadingDigits elements here. Now, if we have a look at how GlobalPhone stores the leadingDigits when it parses the database (here a slight modification of one of your unit tests):

[Test]
public void it_can_generate_data_without_causing_an_exception()
{
var generator = DatabaseGenerator.Load(new WebClient().DownloadString("https://raw.githubusercontent.com/googlei18n/libphonenumber/master/resources/PhoneNumberMetadata.xml"));
var result = generator.RecordData().ToList();
var countryCode44 = result[63];
var leadingDigits = ((IDictionary[]) countryCode44["formats"])[4]["leadingDigits"];
}

...the leadingDigits variable here has the value "7(?:[1-5789]|62)7(?:[1-5789]|624)", i.e. it seems to me that both of the XML node patterns have simply been concatenated into a big long string pattern, which doesn't seem right at all! This seems to be the problem that's causing various formatting issues in an application of ours. Are you able to confirm that this is indeed a bug, or am I missing something? If this is indeed a bug, it probably affects any case where there is more than one leadingDigits XML element, right?

How to convert the xml to json?

Hi, I like your idea of converting the fork to C# and I was really happy to find this. It is just what I need in my .NET application.

Unfortunately I have no idea how to do the Step 2 of the "Installation" section in the readme file. I installed it using the package manager like you explained. - By the way there is no $-sign in this console. The line in Step 1 should be "PM> Install-Package GlobalPhone"

Can you give me a hint? Watching at the original Ruby project does not help me because I does not know anything about Ruby.

Thanks.

how to use GlobalPhoneDbgen

Hi,
It's mentioned that GlobalPhoneDbgen could be used to to convert Google's libphonenumber PhoneNumberMetaData.xml file into a JSON database for GlobalPhone
So how could i do that ??
Thanks in advance :)

No linux support?

How can I get this to work on dotnet on linux with vscode.
-how do i do the conversion?

TryNormalize changed behavior

There is an update in behavior in GlobalPhone 5.0.2 -> 6.0.0.
Before an
_globalPhone.TryNormalize("#08-2 55 55", out normalized, "SE")
returned null
Now it returns
"+46825555"

Is this intentional?

Indian Mobile Numbers starting with 6 not parsing

I tried parsing a number this +9162027XXXXX (Valid Indian Moibile Number)
GlobalPhone.TryParse("+9162027XXXXX", out number, "IN")

but its failing,

Is there any way I can allow numbers starting with 6, for India
or do I have to wait for a new version with this fix and update the next lib version with this fix in my application?

Formatting Issues

Hi,

I've recently downloaded your library and have started running through some tests. I am seeing some weird formatting issues.

First thing, for all the countries I have tested, except US, there seems to be an additional space character in after the first number region. Also the formatting is off.

This is simplified to show results

Example #1

var number = GlobalPhone.GlobalPhone.Parse("07411 111111", "GB");
// returns 074  1111 1111 as number.NationalFormat. Note the extra space after 074.

Also this should be formatted as 07411 111111 per libphonenumber and wikipedia. See http://goo.gl/qAVjHp

I saw similar extra spaces for countries AU, NZ and SG.

Look into merging this pull request into c#

Add #area_code, #local_number to Number

+    test "area_code" do
+      number = context.parse("+61 3 9876 0010")
+      assert_equal "03", number.area_code
+
+      number = context.parse("+44 (0) 20-7031-3000")
+      assert_equal "020", number.area_code
+
+      # Hong Kong has no area code
+      number = context.parse("+852 2699 2838")
+      assert_equal nil, number.area_code
+    end
+
+    test "local_number" do
+      number = context.parse("+61 3 9876 0010")
+      assert_equal "9876 0010", number.local_number
+
+      number = context.parse("+44 (0) 20-7031-3000")
+      assert_equal "7031 3000", number.local_number
+
+      number = context.parse("+852 2699 2838")
+      assert_equal "2699 2838", number.local_number
+    end

Does not parse area code for US numbers

I found this curious that when parsing US phone numbers the area code always returns null. However, when parsing numbers in Europe the area code is populated. Is this a bug or by design?

Normalize returns string with number even when not valid

This test succeeds:

[Test]
public void validating_with_text_not_number_should_return_false()
{
Assert.That(Context.Validate("mobile", "se"), Is.False);
}

And when normalizing the same string used in test above like this:

[Test]
public void normalizing_with_text_not_number_should_return_null()
{
Assert.That(Context.Normalize("mobile", "se"), Is.Null);
}

we get:
Expected: null
But was: "+46662453"

Question around assembly load From NuGet

First of all, thanks for creating this library. It's served me well, and I'm a great fan of it. But it seems your most recent package may have some problems.
I am using it in an app I'm building, using .NET Core 3.0, and getting the error below:
System.IO.FileLoadException: Could not load file or assembly 'PhoneNumbers, Version=8.10.1.0, Culture=neutral, PublicKeyToken=null'. The located assembly's manifest definition does not match the assembly reference. (0x80131040) File name: 'PhoneNumbers, Version=8.10.1.0, Culture=neutral, PublicKeyToken=null' at GlobalPhone.Context..ctor() at GlobalPhone.GlobalPhone.get_Context() at GlobalPhone.GlobalPhone.TryParse(String str, Number& number, String territoryName)
Any help will be greatly appreciated.

No need for nuget package GlobalPhoneCore

The code will probably work on any platform after as can be seen on travis builds. Need to publish new version of GlobalPhone nuget package without the dependencies on Newtonsoft etc.

Object reference not set to an instance of an object Exception

Hi, I am getting an object reference exception using the static method Parse.
I set the DbPath to the json file (I had no trouble generating it successfully with the DbGen tool.
Any help is greatly appreciated.

"message": "Object reference not set to an instance of an object.", 
"stackTrace": "     at GlobalPhone.Territory.Possible(String str)
   at GlobalPhone.Territory.ParseNationalString(String str)
   at GlobalPhone.Parsing.Parse(String str, String territoryName)
   at GlobalPhone.Context.Parse(String str, String territoryName)
   at GlobalPhone.GlobalPhone.Parse(String number, String territoryName)

International phone number is parsed wrongly with extension!!

I think we have problem with Number class.

I passed the phone number "034116999#2405" (2405 is the extension) with country code is TH.
GlobalPhone.TryParse(number, out var globalNumber, territoryName) did a perfect job
but in the Number class, it parsed InternationalString
number.InternationalString = "+66341169992405" ( Which is wrong)

Anyone have any ideas?

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.