Code Monkey home page Code Monkey logo

libphonenumber's Introduction

libphonenumber

golang port of Google's libphonenumber

forthebadge

Build Status GoDoc

Status

This library is fully stable and is used in production by several companies.

Examples

Super simple to use.

To get a phone number

num, err := libphonenumber.Parse("6502530000", "US")

To format a number

// num is a *libphonenumber.PhoneNumber
formattedNum := libphonenumber.Format(num, libphonenumber.NATIONAL)

To get the area code of a number

// Parse the number.
num, err := libphonenumber.Parse("1234567890", "US")
if err != nil {
        // Handle error appropriately.
}

// Get the cleaned number and the length of the area code.
natSigNumber := libphonenumber.GetNationalSignificantNumber(num)
geoCodeLength := libphonenumber.GetLengthOfGeographicalAreaCode(num)

// Extract the area code.
areaCode := ""
if geoCodeLength > 0 {
        areaCode = natSigNumber[0:geoCodeLength]
}
fmt.Println(areaCode)

libphonenumber's People

Contributors

alecthomas avatar alphawong avatar dvrkps avatar f21 avatar fabriziomoscon avatar govindarajan avatar jayd3e avatar jrudder avatar jvictorchen avatar kevinburke avatar kevinburke1 avatar loopfz avatar shahbazahmed1269 avatar steeve avatar themihai avatar ttacon avatar xanderdwyl avatar yerhabe 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

libphonenumber's Issues

Parsing error due to a bug

The national number of phone number +33 07856952 should be 07856952. But the code is returning 78569522 as the result. This is caused by a bug in line

potentialNationalNumber := builder.NewBuilder(normalizedNationalNumber.Byte())

The problem is that we are creating potentialNationalNumber from normalizedNationalNumber.Byte(), which is a pointer. So any change in potentialNationalNumber will also change the value of normalizedNationalNumber.

I will submit a PR to address this issue.

Some valid phone numbers returning false when IsPossibleNumber is called

Example case:

parsedNumber, err := libphonenumber.Parse("+8201038791365", "")
formattedNumber := libphonenumber.Format(parsedNumber, libphonenumber.E164)
fmt.Printf("formatted number: %s \n", formattedNumber)
fmt.Printf("possible: %v \n", libphonenumber.IsPossibleNumber(number))
fmt.Printf("valid: %v \n", libphonenumber.IsValidNumber(number))

returns

formatted number: +821038791365
possible: false
valid: true

This number should be a possible number according to the Google lib source of truth.

I believe this issue was introduced by #79, as commits prior to hash 7104f0e work as expected.

This could potentially be a similar issue to #63, since isPossible is returning false but isValid is returning true.

Test failed at f9c5ddf85ffa9cc802cb511f9ab4733d7d8fbb0e

github.com/ttacon/libphonenumber on master via python
➔ git log | head -1
commit f9c5ddf

github.com/ttacon/libphonenumber on master via python
➔ go test github.com/ttacon/libphonenumber
--- FAIL: TestGetExampleNumberForNonGeoEntity (0.00s)
phonenumberutil_test.go:717: there should be an example 800 number
phonenumberutil_test.go:722: there should be an example number for 979
FAIL
FAIL github.com/ttacon/libphonenumber 0.016s

Add godeps.json

It'll help users not to have to figure out the dependencies on their own and will allow package managers like glide to do their job properly

wrong validation result and mismatched from the official libphonenumber

this is the parsing result from libphonenumber

this is the result from this lib, the result is mismatch

     countryCode := 856
      mobileNumber := "2092420366"
      region := "LA"
      num, err := libphonenumber.Parse(fmt.Sprintf("+%d%s", countryCode, mobileNumber), region)
      if err != nil {
          fmt.Println(err)
          return
      }
      fmt.Println(libphonenumber.IsValidNumber(num))
      // false

what's wrong, should we upgrade the data source or something?

Not accepting UK as a country

"UK" does not seem to be accepted as a country, but "GB" is.

When I run:

var num libphonenumber.PhoneNumber
err := libphonenumber.ParseToNumber("0123456789", "GB", &num)
if err != nil {
	fmt.Println("error with GB:", err)
	return
}
err = libphonenumber.ParseToNumber("0123456789", "UK", &num)
if err != nil {
	fmt.Println("error with UK:", err)
	return
}

I get:
error with UK: invalid country code

However, according to some resources I've checked, +44 is always referred to the calling code of the United Kingdom.

IsValidNumber -- Invalid numbers considered valid

Some invalid numbers (e.g. "+343511234567", "ES", possible pattern = "\d{9}") are not correctly rejected.

This is due to the regexp matching in isNumberPossibleForDesc() which is not strict enough.

I have a fix ready for this, will PR soon.

How do I check if a number is a fixed line number or not?

Hi,

I'm having some trouble figuring out how to check if a given number is a fixed line or a mobile number. I've tried going through the documentation on godoc.org but I was not able to figure it out.

Any help would be much appreciated.

Redundant check, might indicate bug

The following piece of code checks for the same condition twice. The second condition is either redundant, or incorrect:

if len(nationalPrefix) == 0 || len(nationalPrefix) == 0 {
    // If the region doesn't have a national prefix at all,
    // we can safely return the national format without worrying
    // about a national prefix being added.
    formattedNumber = nationalFormat
    break
}
/src/github.com/ttacon/libphonenumber/phonenumberutil.go:1400:6: identical expressions on the left and right side of the '||' operator

Valid phone numbers are not accepted

As an experiment I tried to validate +31101234567. Testing this against the libphonenumber demo shows that it should be flagged as a correct number. When I run this against the golang version I get the following:

Number: country_code:31 national_number:1234567 
Region code: NL
Number is valid: false
    number, err := libphonenumber.Parse(phone, "MY")
    if err != nil {
        log.Printf("Invalid: %v", err.Error())
        return false
    }
    log.Printf("Number: %v", number)
    log.Printf("Region code: %v", libphonenumber.GetRegionCodeForNumber(number))
    log.Printf("Number is valid: %v", libphonenumber.IsValidNumber(number))

It looks like the area code (010) was lost somewhere.

Undefined protoPackageVersion

Go get fails with this, please help :(

$ go get github.com/mattwilliamson/libphonenumber # github.com/mattwilliamson/libphonenumber ../../work/src/github.com/mattwilliamson/libphonenumber/phonemetadata.pb.go:32: undefined: proto.ProtoPackageIsVersion1

Can we have a change log?

Hello,

Can we have some change log to indicate what changes have been introduced for each release? Thus we can refer to what and how big the changes are.

Thank you.

Issue in django-phonenumber-field causing by error in libphonenumber

hi,actually the issue is in django-phonenumber-field and by that german numbers,for example 1765770313 is getting invalid in my application.So when i asked @django-phonenumber field,the response was
"This is an issue in the upstream libphonenumber, probably stemming from a default country code not being set"...
so can you kindly tell me whats going on overall
thanks

Inconsistent Phone number Normalization

1
Input Number: 840938816460
CountryCode: VN
Output Number : 84938816460 (Vietnam number)
2
Input Number: 65082666437
CountryCode: SG
Output Number 65082666437 (expecting 6582666437, Singapore Number)
3
Input Number: 6582666437-0S0O0MEOTHERTAG
CountryCode: SG
Output Number: 6582666437000 (expecting error as it is not a number at all)

Generally there are 2 problems in this issues, 1. inconsistent results comparing test case 1 and 2.
2. The normalizer might have some false positive. Thanks~

How to update the rules to match isoCountry and number type

Hi @ttacon,
I have been using the library for few months and it works great, but sometimes the country and number type are not guessed correctly.
For example there are few exceptions I noticed for UK and Greece.
In UK some numbers country must belong to the Channel Islands so for example

countryTypeException{
			pattern:        "^\\+447781.*",
			isoCountryCode: "GU",
			numType:        "mobile",
			description:    "Sure mobile phones and pagers",
		}

And I found a special case for old greek pager that at the moment returns MOBILE.

It would be great to understand what is the process to update these rules and also import new updates from the original library you ported

Thanks much appreciated

[Question] Any plan to port PhoneNumberToTimeZonesMapper?

I would like to map a phonenumber to the relative timezone.
The Google Java/Javascript library allows it. It would be good to have it in go as well.

The original file is this one:
https://github.com/googlei18n/libphonenumber/blob/3ea1359a3e41bbb0a90ec253c00ba41712fb736b/java/geocoder/src/com/google/i18n/phonenumbers/PhoneNumberToTimeZonesMapper.java

I can help with a PR if @ttacon could provide me with some basic instructions. For example how to import the binary data for the timezone...

Please let me know what is the best way to proceed.

Australian numbers incorrectly classified as having Italian leading zeros

All fixed line and mobile numbers in Australia have a zero prefix. eg. A mobile number looks like 0491 570 156 and a fixed line looks like 02 5550 1234. The leading zero is dropped for international dialling. I believe there are many other countries using a similar approach.

Upstream libphonenumber correctly parses and formats this as +61491570156, but this library does not and produces +610491570156 (note the additional zero).

PS. I tried to dig through the code to track down where this was occurring, but the code is deeply deeply nested (presumably due to being translated from Java). Sorry I couldn't be of more help.

There is a problem about libphonenumber

Hi,ttacon,i use your libphonenumber in my go service,but recently i find a problem,for examople,16601047600 this a valid phonenumber from China Unicom,and it belongs to beijing,but when i use libphonenumber to parse this phonenumber,it tells me ,this number is not a valid number

IsValidNumber return false for Chinese phone

Recently, two new phone numbers were added in China, prefixed with 199 and 166 respectively.

I test with ruby latest phonelib

require 'phonelib'
Phonelib.default_country = "CN"

Phonelib.valid? '19908888188'
=> true

Phonelib.valid? '16608888188'
=> true

a protobuf data update ?

Parse error - national number incorrect for some phone numbers.

If I call

_, err := libphonenumber.Parse("15167706076", "US")
nationalNumber := num.GetNationalNumber()

National number should equal 5167706076...but instead it has a leading 1 - so it is 15167706076.

I looked into the parse code a bit but couldn't find any clear reason as to why this is occurring.

IsPossibleNumber returns false for valid numbers

IsPossibleNumber seems to be returning false even for numbers which are valid according to IsValidNumber. I even tried using an example number via GetExampleNumber itself:

num := libphonenumber.GetExampleNumber("IN")
is_valid := libphonenumber.IsValidNumber(num)
fmt.Printf("is_valid: %v\n", is_valid)
is_possible := libphonenumber.IsPossibleNumber(num)
fmt.Printf("is_possible: %v\n", is_possible)
formattedNum := libphonenumber.Format(num, libphonenumber.E164)
fmt.Printf("number: %v\n", formattedNum)

returns the output:

is_valid: true
is_possible: false
number: +911123456789

I tried this with my own number and even GetExampleNumber("US").

Not go routine safe

Looks like this code is not go routine safe. When I try to run parallel, it is panic-ing.

Please find the trace below.

goroutine 13 [running]:
runtime.throw(0xec0ca0, 0xd)
/usr/local/go/src/runtime/panic.go:527 +0x90 fp=0xc8204e97b8 sp=0xc8204e97a0
runtime.evacuate(0xc0dfa0, 0xc82007df80, 0x0)
/usr/local/go/src/runtime/hashmap.go:825 +0x3b1 fp=0xc8204e9878 sp=0xc8204e97b8
runtime.growWork(0xc0dfa0, 0xc82007df80, 0x1)
/usr/local/go/src/runtime/hashmap.go:791 +0x57 fp=0xc8204e9898 sp=0xc8204e9878
runtime.mapassign1(0xc0dfa0, 0xc82007df80, 0xc8204e99b0, 0xc8204e9978)
/usr/local/go/src/runtime/hashmap.go:433 +0x176 fp=0xc8204e9940 sp=0xc8204e9898
github.com/ttacon/libphonenumber.isNumberPossibleForDesc(0xc8202748b0, 0xa, 0xc8201a1410, 0xc8204e9a10)
/home/someuser/src/github.com/ttacon/libphonenumber/phonenumberutil.go:2051 +0x15e fp=0xc8204e99d8 sp=0xc8204e9940
github.com/ttacon/libphonenumber.isNumberMatchingDesc(0xc8202748b0, 0xa, 0xc8201a1410, 0x0)
/home/someuser/src/github.com/ttacon/libphonenumber/phonenumberutil.go:2063 +0x18a fp=0xc8204e9a70 sp=0xc8204e99d8
github.com/ttacon/libphonenumber.getNumberTypeHelper(0xc8202748b0, 0xa, 0xc8201a4280, 0x2)
/home/someuser/src/github.com/ttacon/libphonenumber/phonenumberutil.go:1983 +0x120 fp=0xc8204e9ab8 sp=0xc8204e9a70
github.com/ttacon/libphonenumber.IsValidNumberForRegion(0xc8202f8180, 0xea7c30, 0x2, 0x0)
/home/someuser/src/github.com/ttacon/libphonenumber/phonenumberutil.go:2110 +0x245 fp=0xc8204e9ba8 sp=0xc8204e9ab8
github.com/ttacon/libphonenumber.IsValidNumber(0xc8202f8180, 0xd)
/home/someuser/src/github.com/ttacon/libphonenumber/phonenumberutil.go:2073 +0x4d fp=0xc8204e9be0 sp=0xc8204e9ba8
bitbucket.org/Test/gondor/common/helpers/numbers.GetPhoneNumber(0xeb4f50, 0xd, 0xea6308, 0x2, 0x0, 0x0, 0x0, 0x0, 0xc8202f8120)
/home/someuser/src/bitbucket.org/Test/gondor/common/helpers/numbers/numbers.go:62 +0x426 fp=0xc8204e9d90 sp=0xc8204e9be0
bitbucket.org/Test/gondor/gollum/gtest_test.playHangupTest(0xc820242a30)
/home/someuser/src/bitbucket.org/Test/gondor/gollum/gtest/bulk_requests_test.go:38 +0x1f1 fp=0xc8204e9f88 sp=0xc8204e9d90
runtime.goexit()
/usr/local/go/src/runtime/asm_amd64.s:1696 +0x1 fp=0xc8204e9f90 sp=0xc8204e9f88
created by bitbucket.org/Test/gondor/gollum/gtest_test.glob.func1.1.1.1
/home/someuser/src/bitbucket.org/Test/gondor/gollum/gtest/bulk_requests_test.go:119 +0x86

testNumberLengthAgainstPattern is returning TOO_SHORT when the number of digits is between 7 and 10

According to the documentation, if the pattern is suggesting that the number should have length of 7 or 10, and when the number actually has length of 8, this function will return TOO_LONG.

// Helper method to check a number against a particular pattern and
// determine whether it matches, or is too short or too long. Currently,
// if a number pattern suggests that numbers of length 7 and 10 are
// possible, and a number in between these possible lengths is entered,
// such as of length 8, this will return TOO_LONG.

But in the current implementation, it's returning TOO_SHORT.

inds := numberPattern.FindStringIndex(number)
    if len(inds) > 0 && inds[0] == 0 && inds[1] == len(number) {
        if inds[1] == len(number) { // Exact match
            return IS_POSSIBLE
        }
        return TOO_LONG // Matches input start but not end
    }

    return TOO_SHORT // Does not match input start

This leads to a weird behavior of duplicating the last digit when a phone number is hence categorized as too long. For example, +1 951178619 will be parsed and formatted into +1 951-178-6199.

Index out of Range.

Passing in a bad number from a pretty big list. I get this Panic.

I will find the number and post it here.

So it seems if the number ends 0111 is the problem.

Try for example
(555) 555-0111

I also Tried 0113 which also failed. I think it sees (011) pattern which is international dialing code from the US.

If I change it to 0133 it works fine

panic: runtime error: index out of range

goroutine 1 [running]:
github.com/ttacon/libphonenumber.parsePrefixAsIdd(0x2083819a0, 0x2084d2af0, 0xa)
go/src/github.com/ttacon/libphonenumber/phonenumberutil.go:2553 +0x291
github.com/ttacon/libphonenumber.maybeStripInternationalPrefixAndNormalize(0x2084d2af0, 0x208456f26, 0x3, 0x10)
go/src/github.com/ttacon/libphonenumber/phonenumberutil.go:2593 +0x463
github.com/ttacon/libphonenumber.maybeExtractCountryCode(0x2084c6e70, 0xd, 0x20844f680, 0x2084d2a80, 0x0, 0x2084ad920, 0xe, 0x0, 0x0)
go/src/github.com/ttacon/libphonenumber/phonenumberutil.go:2470 +0x1e8
github.com/ttacon/libphonenumber.parseHelper(0x208467a70, 0xe, 0x1c12f0, 0x2, 0x100, 0x2084ad920, 0x0, 0x0)
go/src/github.com/ttacon/libphonenumber/phonenumberutil.go:2848 +0x519
github.com/ttacon/libphonenumber.ParseToNumber(0x208467a70, 0xe, 0x1c12f0, 0x2, 0x2084ad920, 0x0, 0x0)
go/src/github.com/ttacon/libphonenumber/phonenumberutil.go:2731 +0x6c
github.com/ttacon/libphonenumber.Parse(0x208467a70, 0xe, 0x1c12f0, 0x2, 0x208467a70, 0x0, 0x0)
go/src/github.com/ttacon/libphonenumber/phonenumberutil.go:2724 +0x8a
main.main()

AR numbers -- weird behaviour with transformation rule

An AR number such as "+541151123456" is not parsed correctly and is thus deemed invalid by the go lib.

The transform rule is badly applied in maybeStripNationalPrefixAndCarrierCode: it originates from the subgroup logic in this function.

I have a fix ready for this, will PR soon.

$ go test
--- FAIL: TestARNumberTransformRule (0.00s)
phonenumberutil_test.go:730: Number country_code:54 national_number:9191919293 should be valid for region AR
phonenumberutil_test.go:734: Expected '+541151123456', got '+549191919293'
FAIL
exit status 1

Go get fails with this

$ go get github.com/ttacon/libphonenumber

github.com/ttacon/libphonenumber

../../../work/src/github.com/ttacon/libphonenumber/phonemetadata.pb.go:32: undefined: proto.ProtoPackageIsVersion1

If i comment the line out, I get a panic when i do this

fmt.Println(libphonenumber.IsNumberMatch("+91-9573750192", "9573750192"))

Error >>

panic(0x105a80, 0xc4201a6a00)
/usr/local/go/src/runtime/panic.go:500 +0x1a1
github.com/golang/protobuf/proto.Merge(0x1b3d40, 0x0, 0x1b3d40, 0xc4201a0fc0)
/Users/Raghav/work/src/github.com/golang/protobuf/proto/clone.go:64 +0x33c
github.com/ttacon/libphonenumber.isNumberMatchWithNumbers(0xc4201a0fc0, 0xc4201a1620, 0x131433)
/Users/Raghav/work/src/github.com/ttacon/libphonenumber/phonenumberutil.go:3066 +0x49
github.com/ttacon/libphonenumber.isNumberMatchWithOneNumber(0xc4201a0fc0, 0x132460, 0xa, 0x2)
/Users/Raghav/work/src/github.com/ttacon/libphonenumber/phonenumberutil.go:3199 +0x16f
github.com/ttacon/libphonenumber.IsNumberMatch(0x132de0, 0xe, 0x132460, 0xa, 0x0)
/Users/Raghav/work/src/github.com/ttacon/libphonenumber/phonenumberutil.go:3148 +0x275

init function causes memory leak.

Here is some information from pprof :

.../vendor/github.com/ttacon/libphonenumber.init.4 in .../vendor/github.com/ttacon/libphonenumber/phonenumberutil.go
0 1.01MB (flat, cum) 100% of Total
. . 3253: }
. . 3254: return metadata.GetMobileNumberPortableRegion()
. . 3255:}
. . 3256:
. . 3257:func init() {
. 1.01MB 3258: err := loadMetadataFromFile("US", 1)
. . 3259: if err != nil {
. . 3260: // better to die on start up
. . 3261: panic(err)
. . 3262: }

Update metadata file and generated code from latest proto file

I am facing a problem with respect to Indian phone numbers starting with digit 6. For example the number +916290535046 represents a valid Indian mobile number, but this library marks it as invalid.
I tried it with official Javascript library and it says the number is valid.

I tried updating the generated code using make, but I get errors like this while building the library:
./phonenumberutil.go:2369:63: regionMetadata.GetGeneralDesc().GetPossibleNumberPattern undefined (type *PhoneNumberDesc has no field or method GetPossibleNumberPattern)

It seems they have deleted the method PhoneNumberDesc.GetPossibleNumberPattern() (refer following commit in official libphonenumber github commit here), which is being used in file phonenumberutil.go, and hence metadata files can't be updated.

Then, when I tried replacing GetPossibleNumberPattern() with GetNationalNumberPattern(), some of the existing tests started failing.

@ttacon How do we proceed to fix this? Otherwise we may have to switch to other library.
Let me know if I can help.

Local phone numbers for US

If I have:
num, err := Parse("320-5478", "US")

I should get an error. AM I right? But I get +13205478.
I mean that this number does not include domestic (state) code.

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.