Coder Social home page Coder Social logo

ruimarinho / google-libphonenumber Goto Github PK

View Code? Open in Web Editor NEW
1.4K 30.0 142.0 5.73 MB

The up-to-date and reliable Google's libphonenumber package for node.js.

Home Page: https://ruimarinho.github.io/google-libphonenumber

License: Other

JavaScript 99.01% HTML 0.64% Shell 0.35%
libphonenumber phone parser formatter

google-libphonenumber's Introduction

google-libphonenumber

The up-to-date and reliable Google's libphonenumber package for node.js. Zero dependencies.

Status

npm version build status install size

Introduction

Google's libphonenumber is a library that parses, formats, stores and validates international phone numbers. It is used by Android since version 4.0 and is a phenomenal repository of carrier metadata.

Although it compiles down to Java, C++ and JS, its JS port is tightly coupled to the Google Closure library. This makes it more difficult to directly require and use the code on a node.js project.

Google eventually started publishing google-closure-library directly to NPM, ending years of ill-maintained community packages. However, running the original library on node.js remains a cumbersome process.

After all these years, Google's libphonenumber is still not officially available on NPM. What is the best way to use Google's libphonenumber on node.js then? If you're looking for a convenient and easy method, that's what this package is all about.

Installation

Install the package via npm:

npm install --save-prod google-libphonenumber

Usage

The following is a simple phone information extraction example similar to what can be viewed on the official demo page.

⚠️ Most libphonenumber functions expect to receive an instance of libphonenumber.PhoneNumber which can be obtained by calling phoneUtil.parse or phoneUtil.parseAndKeepRawInput on a raw (string) number, otherwise it will throw errors like TypeError: a.getCountryCodeOrDefault is not a function.

This will work:

phoneUtil.isValidNumberForRegion(phoneUtil.parse('202-456-1414', 'US'), 'US');

This will not work:

phoneUtil.isValidNumberForRegion('202-456-1414', 'US');

More API examples after parsing the raw string:

// Require `PhoneNumberFormat`.
const PNF = require('google-libphonenumber').PhoneNumberFormat;

// Get an instance of `PhoneNumberUtil`.
const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

// Parse number with country code and keep raw input.
const number = phoneUtil.parseAndKeepRawInput('202-456-1414', 'US');

// Print the phone's country code.
console.log(number.getCountryCode());
// => 1

// Print the phone's national number.
console.log(number.getNationalNumber());
// => 2024561414

// Print the phone's extension.
console.log(number.getExtension());
// =>

// Print the phone's extension when compared to i18n.phonenumbers.CountryCodeSource.
console.log(number.getCountryCodeSource());
// => FROM_DEFAULT_COUNTRY

// Print the phone's italian leading zero.
console.log(number.getItalianLeadingZero());
// => false

// Print the phone's raw input.
console.log(number.getRawInput());
// => 202-456-1414

// Result from isPossibleNumber().
console.log(phoneUtil.isPossibleNumber(number));
// => true

// Result from isValidNumber().
console.log(phoneUtil.isValidNumber(number));
// => true

// Result from isValidNumberForRegion().
console.log(phoneUtil.isValidNumberForRegion(number, 'US'));
// => true

// Result from getRegionCodeForNumber().
console.log(phoneUtil.getRegionCodeForNumber(number));
// => US

// Result from getNumberType() when compared to i18n.phonenumbers.PhoneNumberType.
console.log(phoneUtil.getNumberType(number));
// => FIXED_LINE_OR_MOBILE

// Format number in the E164 format.
console.log(phoneUtil.format(number, PNF.E164));
// => +12024561414

// Format number in the original format.
console.log(phoneUtil.formatInOriginalFormat(number, 'US'));
// => (202) 456-1414

// Format number in the national format.
console.log(phoneUtil.format(number, PNF.NATIONAL));
// => (202) 456-1414

// Format number in the international format.
console.log(phoneUtil.format(number, PNF.INTERNATIONAL));
// => +1 202-456-1414

// Format number in the out-of-country format from US.
console.log(phoneUtil.formatOutOfCountryCallingNumber(number, 'US'));
// => 1 (202) 456-1414

// Format number in the out-of-country format from CH.
console.log(phoneUtil.formatOutOfCountryCallingNumber(number, 'CH'));
// => 00 1 202-456-1414

Using the "As You Type" Formatter

The "As You Type" formatter is a specialized tool that show the formatting progress as it attempts to discover the right format for the given number. It requires registering every keystroke (input digit) on a new instance of the AsYouTypeFormatter as shown below.

// Require `AsYouTypeFormatter`.
const AsYouTypeFormatter = require('google-libphonenumber').AsYouTypeFormatter;
const formatter = new AsYouTypeFormatter('US');

console.log(formatter.inputDigit('2')); // => 2
console.log(formatter.inputDigit('0')); // => 20
console.log(formatter.inputDigit('2')); // => 202
console.log(formatter.inputDigit('-')); // => 202-
console.log(formatter.inputDigit('4')); // => 202-4
console.log(formatter.inputDigit('5')); // => 202-45
console.log(formatter.inputDigit('6')); // => 202-456
console.log(formatter.inputDigit('-')); // => 202-456-
console.log(formatter.inputDigit('1')); // => 202-456-1
console.log(formatter.inputDigit('4')); // => 202-456-14
console.log(formatter.inputDigit('1')); // => 202-456-141
console.log(formatter.inputDigit('4')); // => 202-456-1414

// Cleanup all input digits from instance.
formatter.clear();

Methods

A quick glance at Google's libphonenumber rich API. Descriptions sourced from original files.

i18n.phonenumbers.PhoneNumberUtil

The class that offers the main utilities to work with phone numbers, such as formatting, parsing and validating.

Highlights:

  • format(number, numberFormat) - formats a phone number in the specified format using default rules.
  • formatInOriginalFormat(number, regionCallingFrom) - formats a phone number using the original phone number format that the number is parsed from.
  • formatOutOfCountryCallingNumber(number, regionCallingFrom) - formats a phone number for out-of-country dialing purposes.
  • getNumberType(number) - gets the type of a valid phone number.
  • getRegionCodeForNumber(number) - returns the region where a phone number is from.
  • isPossibleNumber(number) - returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code).
  • isValidNumber(number) - tests whether a phone number matches a valid pattern.
  • isValidNumberForRegion(number, regionCode) - tests whether a phone number is valid for a certain region.
  • parseAndKeepRawInput(numberToParse, defaultRegion) - parses a string and returns it in proto buffer format while keeping the raw input value.
  • parse(numberToParse, defaultRegion) - parses a string and returns it in proto buffer format.

i18n.phonenumbers.PhoneNumber

The type of the phone returned after a string number has been parsed via PhoneNumberUtil.parse() or PhoneNumberUtil.parseAndKeepRawInput().

Highlights:

  • getCountryCode()
  • getCountryCodeSource()
  • getExtension()
  • getItalianLeadingZero()
  • getNationalNumber()
  • getRawInput()

i18n.phonenumbers.CountryCodeSource

Lists the following enums in order to compare them with the output of Phone.getCountryCodeSource():

  • CountryCodeSource.UNSPECIFIED
  • CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN
  • CountryCodeSource.FROM_NUMBER_WITH_IDD
  • CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN
  • CountryCodeSource.FROM_DEFAULT_COUNTRY

i18n.phonenumbers.PhoneNumberFormat

Lists the following enums in order to pass them to PhoneNumberUtil.format():

  • PhoneNumberFormat.E164
  • PhoneNumberFormat.INTERNATIONAL
  • PhoneNumberFormat.NATIONAL
  • PhoneNumberFormat.RFC3966

i18n.phonenumbers.PhoneNumberType

Lists the following enums in order to compare them with the output of PhoneNumberUtil.getNumberType():

  • PhoneNumberType.FIXED_LINE
  • PhoneNumberType.MOBILE
  • PhoneNumberType.FIXED_LINE_OR_MOBILE
  • PhoneNumberType.TOLL_FREE
  • PhoneNumberType.PREMIUM_RATE
  • PhoneNumberType.SHARED_COST
  • PhoneNumberType.VOIP
  • PhoneNumberType.PERSONAL_NUMBER
  • PhoneNumberType.PAGER
  • PhoneNumberType.UAN
  • PhoneNumberType.VOICEMAIL
  • PhoneNumberType.UNKNOWN

i18n.phonenumbers.ShortNumberInfo

Highlights:

  • connectsToEmergencyNumber(number, regionCode) - tests whether the short number can be used to connect to emergency services when dialed from the given region.
  • isPossibleShortNumber(number) - tests whether a short number is a possible number.
  • isPossibleShortNumberForRegion(number, regionDialingFrom) - tests whether a short number is a possible number when dialed from the given region.
  • isValidShortNumber(number) - tests whether a short number is a possible number.
  • isValidShortNumberForRegion(number, regionDialingFrom) - tests whether a short number matches a valid pattern in a region.
// Get an instance of `ShortNumberInfo`.
const shortInfo = require('google-libphonenumber').ShortNumberInfo.getInstance();

// Get an instance of `PhoneNumberUtil`.
const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

// Result from connectsToEmergencyNumber().
console.log(shortInfo.connectsToEmergencyNumber('911', 'US'));
// => true

// Result from isPossibleShortNumber().
console.log(shortInfo.isPossibleShortNumber(phoneUtil.parse('123456', 'FR')));
// => true

// Result from isPossibleShortNumberForRegion().
console.log(shortInfo.isPossibleShortNumberForRegion(phoneUtil.parse('123456', 'FR'), 'FR'));
// => true

Unavailable methods and classes

The following methods or classes are unavailable on the original JS port of Google's libphonenumber:

  • findNumbers - finds numbers in text (useful for highlighting or linking phone numbers inside text messages).
  • PhoneNumberOfflineGeocoder - provides geographical information related to a phone number.
  • PhoneNumberToCarrierMapper - provides carrier information related to a phone number.
  • PhoneNumberToTimeZonesMapper - provides timezone information related to a phone number.

Notes

Metadata issues

Most of the issues submitted to this repository are related to carrier metadata - things like unexpected phone validations, errors in formatting numbers, unknown carriers and so on.

First, try the same input using the official demo page. If the result is different, then it might mean that a metadata update is due on this package, as the demo page always runs on the latest and official metadata version.

If the result is the same, it means there might be an issue with the currently available metadata. In that case, you should report your issue in the original project's issue tracker (moved out of GitHub on 05/12/2017).

This note will be posted on every issue regarding metadata troubles and it will be automatically closed.

Differences from other packages

google-libphonenumber does not try to be more than what it really is - a pre-compiled Google libphonenumber bundle that works on node.js. It is a 1:1 mirror of the original library without any further simplifications or optimizations.

  • All classes available from libphonenumber are exported as-is. No magic methods.
  • Always based on the latest google-closure library version available from Google with performance and bug fixes.
  • Relies on a simplified and well-documented update process to keep the underlying libphonenumber library always up-to-date.

If you're looking for a slightly simpler API, you should try awesome-phonenumber. It is based on the same concepts of this package but changes the API in order to make it more user friendly. You run the risk of bumping into other bugs and you'll have to learn new API types, but that's the necessary trade-off that the author made for achieving a generally better looking API.

libphonenumber-js is a much more radical approach to Google's libphonenumber. It is a rewrite of the original library based on its source phone metadata but implemented without depending on the Google Closure library. It also offers a tool to reduce the metadata to a set of countries which might be useful for frontend projects. It has several caveats, many of which make a lot of sense depending on the project, but you will have to ascertain those yourself.

Webpack

There have been some users reporting successful but also unsuccessful usage with Webpack. While I don't personally use it, I'm 100% supportive of pull requests adding modifications that allow this package to better interact with it.

Chrome Extensions

Google Closure Compiler API, a serviced provided by Google to compile code online via its Closure library, may not always return fully compliant UTF-8-encoded output.

Loading extensions using this library on Google Chrome and other Chromium-based browsers may result in the following error when compiled with webpack:

Could not load file 'file.js' for content script. It isn't UTF-8 encoded.

While the local Java-based version supports a parameter which would let us workaround this issue at the source using --charset=US-ASCII, the online API version, which is a lot more convenient to use, does not offer support for an equivalent parameter (e.g. output_charset=US-ASCII).

In order to workaround this issue when using webpack, make sure to output US-ASCII characters only when defining TerserPlugin options, as demonstrated below:

optimization: {
  minimize: process.env.NODE_ENV !== 'development',
  minimizer: [
    new TerserPlugin({
      terserOptions: {
        output: {
          ascii_only: true
        }
      },
    }),
  ]
}

Tests

A small subset of tests guarantees that the main library functions are working as expected and are correctly exported. The actual heavy lifting is done by libphonenumber's extensive test suite.

npm test

Release

npm version [<newversion> | major | minor | patch] -m "Release %s"

Acknowledgments

The exceptional work on libphonenumber was made possible by these committers and contributors.

Licenses

This package is licensed under MIT. The bundled libphonenumber library is licensed under Apache 2.0.

google-libphonenumber's People

Contributors

delaguilaluis avatar dependabot[bot] avatar ex-kaiser avatar fixe avatar giggsey avatar kohenkatz avatar manuelvillar avatar mathieumg avatar ruimarinho avatar scop avatar styfle 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-libphonenumber's Issues

Namespace is trademark infringement

Hi,

Nice to see that you maintain a project like this, but it heavily infringes on Googles trademark, and is in no way related to, or maintained by Google. You should in my opinion look to change this.

Please refer to the Google Trademarks page for more information:

We cannot approve any company names or application names that incorporate a Google trademark, or that are confusingly similar to Google's trademarks.

https://www.google.com/permissions/faq.html

Getting an assertion error on require of the library.

Just started getting this error, have a version of the code running perfectly on our live server. Running "google-libphonenumber": "^3.0.0", on node v8.1.4, npm 5.3.0

{ 
  err:{ 
    AssertionError
      at new goog.asserts.AssertionError (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:1208:20)
      at Object.goog.asserts.doAssertFailure_ (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:1226:7)
      at Object.goog.asserts.assert (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:1233:53)
      at new goog.proto2.FieldDescriptor (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:1960:16)
      at Function.goog.proto2.Message.createDescriptor (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:2255:22)
      at i18n.phonenumbers.PhoneMetadata.getDescriptor (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:3130:79)
      at i18n.phonenumbers.PhoneMetadata.goog.proto2.Message (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:2080:23)
      at new i18n.phonenumbers.PhoneMetadata (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:2592:23)
      at Object.1 (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:4684:56)
      at s (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:1:690)
      at e (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:1:861)
      at **PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:1:879
      at i (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:1:150)
      at Object.<anonymous> (**PATH**/node_modules/google-libphonenumber/dist/libphonenumber.js:1:392)
      at Module._compile (module.js:569:30)
      at Object.Module._extensions..js (module.js:580:10)
      at Module.load (module.js:503:32)
      at tryModuleLoad (module.js:466:12)
      at Function.Module._load (module.js:458:3)
      at Module.require (module.js:513:17)
      at require (internal/module.js:11:18)
      at Object.<anonymous> (**PATH**//orders/data/order-container.js:5:21)
    message: 'Assertion failed',
    reportErrorToServer: true,
    messagePattern: 'Assertion failed' 
  }
}

the code that triggers the error:

const Container = require('./container');
const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
const PNF = require('google-libphonenumber').PhoneNumberFormat;

class OrderContainer extends Container {}

the const phoneUtil line is where it is throwing the error. I'm not sure what changed, we haven't been working in this section of the code so it is odd for it to have started erroring.

Usage with webpack on the browser - follow up https://github.com/seegno/google-libphonenumber/issues/38

Hello,

When bundling with webpack, I'm getting this warning, like in #38:

WARNING in ./~/google-libphonenumber/dist/browser/libphonenumber.js
Critical dependencies:
1:487-494 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
 @ ./~/google-libphonenumber/dist/browser/libphonenumber.js 1:487-494

This is because you have on package.json:
"browser": "dist/browser/libphonenumber.js",

Webpack will resolve the import to this file by default (unless you are using webpack with 'target': 'node' for usage in node.js, which is not the most common usage).

I don't know if taking this line from the package.json will break browserify builds (I'm not experient with browserify), but from what I can tell from other libraries, this is not needed.

So what is the difference between dist/browser/libphonenumber.js and dist/libphonenumber ?
Can we just keep the 'main' entry on package.json?

Format German phones

Hello,

I have a German phone number like this (4906) 227-7474 and I want to format into international format

var PNF = require('google-libphonenumber').PhoneNumberFormat;
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
var phoneNumber = phoneUtil.parse('(4906) 227-7474', 'DE');
phoneUtil.format(phoneNumber, PNF.INTERNATIONAL);
//phoneUtil.isValidNumber(phoneNumber) is true

I got +49 4906 2277474 but I want to get 49 6227 7474

How can I get it?

FYI:
For Germany https://en.wikipedia.org/wiki/List_of_dialling_codes_in_Germany#06
49 - country code
06 - area code

Thx, Vitaly

incorrect handling any phone numbers with 4-digit country code

Try to select any country with 4-digit country code

code example
mask = phoneUtil.parse(text, country.iso2); //where text save text in input w/o plus
number = phoneUtil.format(mask, PNF.INTERNATIONAL)
// For any 4-digit numbers, started from 1 (+1876, Jamaica) numbers incorrect detected us U.S. number

getNumberType returning 1

In the demo getNumberType() seems to return MOBILE but in my code I am getting 1

   var mobileNumberValidator = require('google-libphonenumber').PhoneNumberUtil.getInstance();
   var parsedMobileNumber = mobileNumberValidator.parse(mobileNumber, 'GB');
   var isMobile = mobileNumberValidator.getNumberType(parsedMobileNumber);
   console.log(isMobile) // This is printing: 1

I would like to return MOBILE like in the demo, is there something that I am doing wrong?

Difference in output when parsing +2349068084779

Running phone number in subject through https://rawgit.com/googlei18n/libphonenumber/master/javascript/i18n/phonenumbers/demo-compiled.html (w/o default country or carrier code) gives the following output:

****Parsing Result:****
{"country_code":234,"national_number":9068084779,"raw_input":"+2349068084779","country_code_source":1}

****Validation Results:****
Result from isPossibleNumber(): true
Result from isValidNumber(): true
Phone Number region: NG
Result from getNumberType(): MOBILE

****Formatting Results:**** 
E164 format: +2349068084779
Original format: +234 906 808 4779
National format: 0906 808 4779
International format: +234 906 808 4779
Out-of-country format from US: 011 234 906 808 4779
Out-of-country format from Switzerland: 00 234 906 808 4779

****AsYouTypeFormatter Results****
Char entered: + Output: +
Char entered: 2 Output: +2
Char entered: 3 Output: +23
Char entered: 4 Output: +234 
Char entered: 9 Output: +234 9
Char entered: 0 Output: +234 90
Char entered: 6 Output: +234 9 06
Char entered: 8 Output: +234 9 068
Char entered: 0 Output: +234 9 068 0
Char entered: 8 Output: +234 9 068 08
Char entered: 4 Output: +234 9 068 084
Char entered: 7 Output: +234 9 068 0847
Char entered: 7 Output: +234 906 808 477
Char entered: 9 Output: +234 906 808 4779

As we can see, it's valid phone number. Doing the same using google-libphonenumber produces "unknown phone number". It seems library is up to date with https://github.com/googlei18n/libphonenumber and yet it misbehaves. Any thoughts?

getCountryCodeOrDefault is not a function

const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
const invalidNumber = '+12223334444';
console.log(`${invalidNumber} is valid: ${phoneUtil.isValidNumber(invalidNumber)}`);

Error message was TypeError: a.getCountryCodeOrDefault is not a function

Looked into /dist/libphonenumber.js a bit and could not find getCountryCodeOrDefault() from there.

Thanks.

Types

Adds .d.ts for type checking in VSCode and others, please.

Phone number validation fails for numbers starting with 8209****** for IN region

Numbers starting with 8209****** shows invalid number for the given region 'IN'. Here is the npm runkit demo for the same.

https://runkit.com/592d3e4bb70f37001158b54d/592d3e4bb70f37001158b54e

However, the API call with the latest version of google-libphonenumber, shows the accurate result.

http://libphonenumber.appspot.com/phonenumberparser?number=%2B91+8209890000

My assumption is there is something wrong with the implementation.

Here is the complete implementation as it is from npm runkit of google-libphonenumber

var phoneUtil = require("google-libphonenumber").PhoneNumberUtil.getInstance();
var phoneNumber0 = "+918209000000";
var phoneNumber1 = "+918197800510";
var phoneNumber2 = "+918209890000";
var phone0 = phoneUtil.parse(phoneNumber0);
var phone1 = phoneUtil.parse(phoneNumber1);
var phone2 = phoneUtil.parse(phoneNumber2);
console.log(phoneUtil.isValidNumber(phone0)); // failed
console.log(phoneUtil.isValidNumber(phone1)); // success
console.log(phoneUtil.isValidNumber(phone2)); // failed

phoneUtil.getNumberType causes error

I'm getting the following exception when using:

phoneUtil.getNumberType('4477516575751')

Error:

Error: Uncaught (in promise): TypeError: a.getCountryCodeOrDefault is not a function
TypeError: a.getCountryCodeOrDefault is not a function
at i18n.phonenumbers.PhoneNumberUtil.getRegionCodeForNumber (libphonenumber.js:4269)
at i18n.phonenumbers.PhoneNumberUtil.getNumberType (libphonenumber.js:4216)

basic usage question on how to get valid number function/property

Sorry if this was in the demo or documentation somewhere, but how can I get the following from a number using this library? Any documentation or samples on how to get this from a

****Validation Results:****
         Result from isPossibleNumber()
         Result from isValidNumber()
         Result from isValidNumberForRegion()
         Result from getNumberType()

  ****Formatting Results:****
         E164 format

Observation with India phone number parsing

`var region = 'IN';
var phone = '4155216849';
var phoneNumber = phoneUtil.parse(phone, region);

console.log(phone + ' isValid ' + phoneUtil.isValidNumber(phoneNumber));
console.log(phone + ' number type ' + phoneUtil.getNumberType(phoneNumber));
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));`

Output:

4155216849 isValid true

4155216849 number type 0

+91 4155 216 849

I tried dialing this number in India and seems its not a valid number in India.

Unable to Access RegionCode

If you take a look at the google tests, you can see that you are able to access a RegionCode dictionary right off of the main lib. However, this comes back undefined:

> var libphonenumber = require('google-libphonenumber')
undefined
> libphonenumber.RegionCode
undefined

Any thoughts on how this is missing?

phoneUtil.isValidNumberForRegion always gives me false

hi there! Thanks for awesome tool!
one thing I wanna report though: when parsing my Canadian cell phone number isValidNumber() gives me 'false'. Here're the steps to reproduce:

// install lib
npm install google-libphonenumber // installs: [email protected]

// check node version
node --version
v8.7.0

// run node
node

// Require PhoneNumberFormat.
var PNF = require('google-libphonenumber').PhoneNumberFormat;

// Get an instance of PhoneNumberUtil.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

// parse
var phone_number = phoneUtil.parse("+15197227878", "CA"); // also tried "US"

// check if parsed ok
phoneUtil.isValidNumber(phone_number);
true
phoneUtil.format(phone_number, PNF.E164);
'+15197227878'

// check if valid for region (always gives me false)
phoneUtil.isValidNumberForRegion(phone_number)
false

Thanks,
Dmitry Shevkoplyas

'browser' version does not seem ready to usage inside a browser

I have loaded in an HTML page the code stored in the dist/browser directory.
I cannot find any global variable ready to be called by my custom code.

My view is that the only point of having a dist/browser directory is to offer standalone browser-ready code, equipped with a local README that explains how to use it.

Invalid country calling code when using unknown region

I'm trying to format 44 20 7928 5211 in E164 with the expected output of +442079285211

However when I parse it with the US region code it is deemed an invalid number, and when i parse it with the ZZ code I get an invalid country code error. Is there any recommended way of parsing a number when there's no default country code? It seemed like ZZ would be the right approach.

List of country codes

I see there is some list of region codes, but it doesn't contain the full name of the country and it doesn't have the ISD code for that country eg. +1 for US. Does it make sense to add this in to this library? Is there some other library that includes this? I guess I could create one manually.

PhoneMetadataCollection goog.require'd but not used

/app/node_modules/google-libphonenumber/src/phonenumberutil.js:45: ERROR - 'i18n.phonenumbers.PhoneMetadataCollection' goog.require'd but not used
goog.require('i18n.phonenumbers.PhoneMetadataCollection');
^

1 error(s), 0 warning(s)

Use uncompressed source

I'm using this with webpack, and it tells me:

WARNING in .//google-libphonenumber/dist/browser/libphonenumber.js
Critical dependencies:
1:487-494 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
@ ./
/google-libphonenumber/dist/browser/libphonenumber.js 1:487-494

Which seems sensible. I'm not sure about the buildprocess being used here. Is it possible to use the uncompresed files as input to browserify/webpack?

Warning about pre-built source when using webpack

When using google-libphonenumber installed via npm with webpack, I get the following warning on each build. I believe it is common to provide both source and dist files in node packages, am I right? That should solve this problem.

WARNING in ./~/google-libphonenumber/dist/libphonenumber.js
Critical dependencies:
1:487-494 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
 @ ./~/google-libphonenumber/dist/libphonenumber.js 1:487-494

isValidNumber throws an error on basic invocation

Just tried it on a blank state:

var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
phoneUtil.isValidNumber('1234');

throws:

TypeError: a.getCountryCodeOrDefault is not a function

update: doesn't seem to work with valid number either, tried the same example like in the browser demo, aka my phone number. the browser demo worked, the node one didn't.

isValidNumber always returns false

I have tried numerous ways to validate a number with isValidNumber() but it always returns false. For example:

phoneUtil.isValidNumberForRegion( phoneUtil.parseAndKeepRawInput('5555555555', 'US'), 'US')

returns false even though parseAndKeepRawInput returns a valid phone object. Scouring the docs and looking at the demo, isPossibleNumber seems to be the only method that indicates a valid phone number. Has isValidNumber been deprecated?

throw flag

Hello,

would it be possible/feasible/allowable/... to pass a flag to choose if we want to throw an error or receive an error string (ideally in an 'err' property)?

I'm using your package in the sync validate function of redux-forms and i need to try...catch every time to not destroy what the user is typing when i could use the error string to show the error with internationalization when the user corrects his input.

Importing from typescript doesn't work.

Hi I'm trying to use this lib in a typescript project, when I do import { PhoneNumberUtil, PhoneNumber, PhoneNumberFormat, AsYouTypeFormatter } from 'google-libphonenumber'; I get an error saying "could not find declaration file for module 'google-libphonenumber'"

There's a @types/google-libphonenumber package but it has outdated definitions, thus it doesn't have all functionality (like extractPossibleNumber)

Is it possible to use this module with typescript?

Thanks.

assertion error

var gp = require('google-libphonenumber').PhoneNumberUtil.getInstance();

causes this error

number.js:1058
throw a;
^
AssertionError: Assertion failed
at new goog.asserts.AssertionError (...../node_modules/google-libphonenumber/dist/libphonenumber.js:1051:20)
at Object.goog.asserts.doAssertFailure_ (..../node_modules/google-libphonenumber/dist/libphonenumber.js:1068:7)
at Object.goog.asserts.assert as assert
at new goog.proto2.FieldDescriptor (..../node_modules/google-libphonenumber/dist/libphonenumber.js:1553:16)
at Function.goog.proto2.Message.createDescriptor (..../node_modules/google-libphonenumber/dist/libphonenumber.js:2069:22)
at i18n.phonenumbers.PhoneMetadata.getDescriptor (..../node_modules/google-libphonenumber/dist/libphonenumber.js:2946:117)
at goog.proto2.Message (..../node_modules/google-libphonenumber/dist/libphonenumber.js:1897:23)
at new i18n.phonenumbers.PhoneMetadata (..../node_modules/google-libphonenumber/dist/libphonenumber.js:2411:23)
at Object. (..../node_modules/google-libphonenumber/dist/libphonenumber.js:4432:56)
at Module._compile (module.js:435:26)

PhoneNumberOfflineGeocoder ?

Hello,

i'm trying to get the geo info for a number but cant seen to find the PhoneMetadataCollection function/values ??

i even searched the source but not luck 😨

Thanks

Phone number validation fails for numbers starting with 77******** for IN region

Numbers starting with 77******** shows invalid number for the given region 'IN'.
The API call with the latest version of google-libphonenumber, shows the wrong result for isValidNumber()

Have filed the bug with Google Phone lib as well :
https://issuetracker.google.com/issues/69244622

This is Google's API response :
http://libphonenumber.appspot.com/phonenumberparser?number=%2B91+7707059626

Need to fix this, provided Google API is fixed first. Adding is as a TODO .

Here is the complete implementation as it is from npm runkit of google-libphonenumber

var phoneUtil = require("google-libphonenumber").PhoneNumberUtil.getInstance();
var phoneNumber0 = "+917707059626";
var phoneNumber1 = "+918197800510";
var phoneNumber2 = "+917707111289";
var phone0 = phoneUtil.parse(phoneNumber0);
var phone1 = phoneUtil.parse(phoneNumber1);
var phone2 = phoneUtil.parse(phoneNumber2);
console.log(phoneUtil.isValidNumber(phone0)); // failed
console.log(phoneUtil.isValidNumber(phone1)); // success
console.log(phoneUtil.isValidNumber(phone2)); // failed

Is 3.0.0 breaking ?

Hi,

I saw in #116 that getNationalSignificantNumber will return an empty string instead of null.

Is this the only breaking change ? Because I saw in the PR code that a lot of code has been deleted.

If there is more, can you list the Breaking changes in the CHANGELOG file ?

Thank you

Update tags from x.y.z to vX.Y.Z

Following npm's convention when using npm version, tags will be updated to include the v prefix. Existing tags will be renamed.

Compatibility with browserify

Just wondering if this library is intended to be usable with browserify. When I require it I get an error "fs.readFileSync is not a function"

getNumberType() returns UNKNOWN for some valid TOLL_FREE number

PhoneNumberUtil phUtil = PhoneNumberUtil.getInstance();
PhoneNumber number1, number2;
number1 = phUtil.parse("1-800-456-1414", "US"); // works fine
number2 = phUtil.parse("1-800-100-8731", "US");
PhoneNumberType pnType = phUtil.getNumberType(number2);

For number1, I get TOLL_FREE, but for number2, I get UNKNOWN.

Any idea why?

isValidNumber failing ?

Hi.

Im trying to use this package in a project but

phoneUtil.isValidNumber(phoneNr);
gives me
TypeError: a.getCountryCodeOrDefault is not a function.

So for testing i tried it out in npm browser test site (link below) and it gave me the same error: https://tonicdev.com/npm/google-libphonenumber

Heres the copy paste code to test:

require("google-libphonenumber")
// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;

// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');

// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414

var phoneNr = {
 "country_code": 41,
 "national_number": 446681800
};
phoneUtil.isValidNumber(phoneNr);

The phoneUtil.format works but not phoneUtil.isValidNumber. I might be doing something wrong but i cant figure out what.
Do you guys get isValidNumber working?

Warning under Webpack

When using the npm (latest v1.0.12) under Webpack, I'm getting this warning message below in my browser console.
Although its just a warning and not a breaking issue, I was wonder if there is a recommended way around it:

./~/google-libphonenumber/dist/browser/libphonenumber.js
Critical dependencies:
1:487-494 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
 @ ./~/google-libphonenumber/dist/browser/libphonenumber.js 1:487-494

Better documentation please

As a new user i'm having a hard time familiarizing myself with this library, the google docs are not helping.

A simple layout of the available classes, methods and their arguments would be ideal.

vm.runInContext(...) - Undefined is not a function

Hi,

I wanted to use your module but, I'm using with this error...:

- Undefined is not a function
vm.runInContext(fs.readFileSync(file), sandbox);

Sorry, I'm a not a expert about NPM... so I can't help "more".

Here how I "use" your package:

$ npm install --save-dev google-libphonenumber

Here my file:

var phoneUtil = require('google-libphonenumber').phoneUtil
[...]
function isPhone(str, countryCode) {
    try {
      phoneUtil.parse(str, countryCode)
      return (true)
    }
    catch(err) {
      return (false)
    }
}

and the full stack trace:

Uncaught TypeError: undefined is not a function index.js:43
loadScript index.js:48
module.exports.load index.js:2
(anonymous function) bootstrap b4bd7468d6ba5d125b49?019c:504
__webpack_require__ bootstrap b4bd7468d6ba5d125b49?019c:76
fn index.js:6
(anonymous function) index.js:57
(anonymous function) bootstrap b4bd7468d6ba5d125b49?019c:504
__webpack_require__ bootstrap b4bd7468d6ba5d125b49?019c:76
fn StringUtils.js:2
dotNetDateRE bootstrap b4bd7468d6ba5d125b49?019c:504
__webpack_require__ bootstrap b4bd7468d6ba5d125b49?019c:76
fn CreateCustomerId.js:4
(anonymous function) bootstrap b4bd7468d6ba5d125b49?019c:504
__webpack_require__ bootstrap b4bd7468d6ba5d125b49?019c:76
fn CreateCustomer.js:8
(anonymous function) bootstrap b4bd7468d6ba5d125b49?019c:504
__webpack_require__ bootstrap b4bd7468d6ba5d125b49?019c:76
fn index.js:23
(anonymous function) bootstrap b4bd7468d6ba5d125b49?019c:504
__webpack_require__ bootstrap b4bd7468d6ba5d125b49?019c:76
fn index.js:537
(anonymous function) bootstrap b4bd7468d6ba5d125b49?019c:504
__webpack_require__ bootstrap b4bd7468d6ba5d125b49?019c:527
(anonymous function) index.js:531
(anonymous function)

Again, sorry I can't help more...

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.