Git Product home page Git Product logo

awesome-phonenumber's Introduction

npm version downloads build status minzipped size Dependency count

Awesome phonenumber parser

This library is a pre-compiled version of Google's libphonenumber, with a slightly simpler interface. It has a minimal footprint - is by far the smallest libphonenumber-based library available on npmjs, and has no dependencies.

TypeScript typings are provided within the package.

Uses libphonenumber v8.13.35

Versions

  • v3:
    • Changed API (although with backwards compatible ABI)
    • Added ESM export
  • v4:
    • Changed API to be much cleaner
      • No constructor
      • No functions on returned object
      • No errors being thrown
    • Not backwards compatible, although like v3 except:
      • The second argument to parsePhoneNumber is an object
        • E.g. { regionCode: 'SE' } instead of a region code string
      • The return value is like toJSON( ) on v3
  • v5:
    • Dropped Node 12 support
  • v6:
    • Dropped Node 16 support

Comparison with other libraries

Since this library is pre-compiled, it doesn't depend on the closure compiler, and needs not load it on start. This makes the library faster and saves you a lot of space. It also means this library is trivial to use in any webpack project (or using any other means to run in the browser).

Among all the popular phone number using Google's libphonenumber (or mimicing it), only this one, google-libphonenumber and libphonenumber-js have decent README's with examples. This may have changed since first doing these benchmarks.

A library should be quick to load (require()), quick to parse first time and all consecutive times. It shouldn't bloat your node_modules, and it should have a small memory footprint, if possible.

The following is the result of a test program which loads the library, then parses a phone number, and then once again. It's called 100 times for each library and the mean values are shown here. Parsing a phone number first time might be slower because of initially compiling/optimizing regular expressions and whatnot. Parsing a phone number a second time will show the speed of likely all future parsing within that process.

Action awesome-phonenumber
2.56.0
(lib 8.12.29)
google-libphonenumber
3.2.22
(lib 8.12.27)
libphonenumber-js
1.9.23
(lib -)
Load library first time 11.0 ms ✅ 29.67 ms 32.87 ms
Parse first phone number 4.3 ms 4.01 ms 3.43 ms ✅
⇒ Load + parse first number 15.3 ms ✅ 33.68 ms 36.3 ms
Parse second phone number 0.78 ms ✅ 0.97 ms 0.92 ms
Increased memory usage 5.12 M ✅ 9.99 M 5.86 M
node_modules size 296 K ✅ 600 K 7.6 M
node_modules files 8 7 ✅ 653

Basic usage

import { parsePhoneNumber } from 'awesome-phonenumber'

const pn = parsePhoneNumber( '0707123456', { regionCode: 'SE' } );
// or on e164 format:
const pn = parsePhoneNumber( '+46707123456' );

// pn is now the same as:
const pn = {
	valid: true,

	number: {
		input: '0707123456',
		e164: '+46707123456',
		international: '+46 70 712 34 56',
		national: '070-712 34 56',
		rfc3966: 'tel:+46-70-712-34-56',
		significant: '707123456',
	},
	possibility: 'is-possible',
	regionCode: 'SE',
	possible: true,
	canBeInternationallyDialled: true,
	type: 'mobile',
	countryCode: 46,
	typeIsMobile: true,
	typeIsFixedLine: false,
};

The return type is ParsedPhoneNumber which is either a ParsedPhoneNumberValid or a ParsedPhoneNumberInvalid. The valid property identifies whether the parsing was successful or not, hence which type is returned.

The format of a successful parsing is:

interface ParsedPhoneNumberValid {
	valid: true;

	number: {
		input: string;
		international: string;
		national: string;
		e164: string;
		rfc3966: string;
		significant: string;
	};
	possibility: PhoneNumberPossibility; // a string union, see below
	regionCode: string;
	possible: boolean;
	canBeInternationallyDialled: boolean;
	type: PhoneNumberTypes; // a string union, see below
	countryCode: number;
	typeIsMobile: boolean;
	typeIsFixedLine: boolean;
}

If the number failed to be parsed, or there was another error, the return type is:

interface ParsedPhoneNumberInvalid {
	valid: false;

	possible: false;
	possibility: 'invalid';
	error?: unknown;
};

API

import {
	parsePhoneNumber,
	getNumberFrom,
	getExample,
	getCountryCodeForRegionCode,
	getRegionCodeForCountryCode,
	getSupportedCallingCodes,
	getSupportedRegionCodes,
	getAsYouType,
} from 'awesome-phonenumber'

parsePhoneNumber

parsePhoneNumber( phoneNumber, { regionCode: string } ) parses a phone number as described above.

The first argument is the phone number to parse, on either national or international (e164, i.e. prefixed with a +) form. If national form, the second argument is required to contain a regionCode string property, e.g. 'SE' for Sweden, 'CH' for Switzerland, etc.

getNumberFrom

import { parsePhoneNumber, getNumberFrom } from 'awesome-phonenumber'

const pn = parsePhoneNumber( '0707654321', { regionCode: 'SE' } );
if ( pn.valid ) {
	const fromJp = getNumberFrom( pn, 'JP' );
	// fromJp is the number to call from Japan:
	fromJp.number === "010 46 70 765 43 21";
}

The return value from getNumberFrom is a PhoneNumberFrom which is either a PhoneNumberFromValid or a PhoneNumberFromInvalid.

The PhoneNumberFromValid is defined as:

interface PhoneNumberFromValid
{
	valid: true;
	number: string;
}

The PhoneNumberFromInvalid is defined as:

interface PhoneNumberFromInvalid
{
	valid: false;
	error?: unknown;
}

getExample

Sometimes you want to display a formatted example phone number for a certain country (and maybe also a certain type of phone number). The getExample function is used for this.

import { getExample } from 'awesome-phonenumber'

getExample( regionCode[, phoneNumberType] ); // Parsed phone number

The phoneNumberType is any of the types defined above.

Example

import { getExample } from 'awesome-phonenumber'

// Get an example Swedish phone number
const example = getExample( 'SE' ); // A ParsedPhoneNumberValid
const exampleMobile = getExample( 'SE', 'mobile' ); // A ParsedPhoneNumberValid

example.number.e164;           // e.g. '+468123456'
exampleMobile.number.e164;     // e.g. '+46701234567'
exampleMobile.number.national; // e.g. '070 123 45 67'

Country codes

There are conversion functions between the 2-character ISO 3166-1 region codes (e.g. 'SE' for Sweden) and the corresponding country calling codes.

import {
	getCountryCodeForRegionCode,
	getRegionCodeForCountryCode,
	getSupportedCallingCodes,
	getSupportedRegionCodes,
} from 'awesome-phonenumber'

getCountryCodeForRegionCode( regionCode );  // -> countryCode
getRegionCodeForCountryCode( countryCode ); // -> regionCode

Example

getCountryCodeForRegionCode( 'SE' ); // -> 46
getRegionCodeForCountryCode( 46 );   // -> 'SE'

Supported calling codes

getSupportedCallingCodes( ); // -> [ calling codes... ]

Supported region codes

getSupportedRegionCodes( ); // -> [ region codes... ]

API types

The API consists of the PhoneNumber class which sometimes uses enums. These are:

Phone number types

type PhoneNumberTypes =
	| 'fixed-line'
	| 'fixed-line-or-mobile'
	| 'mobile'
	| 'pager'
	| 'personal-number'
	| 'premium-rate'
	| 'shared-cost'
	| 'toll-free'
	| 'uan'
	| 'voip'
	| 'unknown'

Phone number possibilities

type PhoneNumberPossibility =
	| 'is-possible'
	| 'invalid-country-code'
	| 'too-long'
	| 'too-short'
	| 'unknown'

Phone number formats

'international'
'national'
'e164'
'rfc3966'
'significant'

As-you-type formatting

You can create an AsYouType class with getAsYouType() to format a phone number as it is being typed.

import { getAsYouType } from 'awesome-phonenumber'

const ayt = getAsYouType( 'SE' );

The returned class instance has the following methods

// Add a character to the end of the number
ayt.addChar( nextChar: string );

// Get the current formatted number
ayt.number( );

// Remove the last character
ayt.removeChar( );

// Replace the whole number with a new number (or an empty number if undefined)
ayt.reset( number?: string );

// Get a ParsedPhoneNumber object representing the current number
ayt.getPhoneNumber( );

All the functions above except getPhoneNumber( ) return the current formatted number as a string.

Example

import { getAsYouType } from 'awesome-phonenumber'

const ayt = getAsYouType( 'SE' );
ayt.addChar( '0' ); // -> '0'
ayt.addChar( '7' ); // -> '07'
ayt.addChar( '0' ); // -> '070'
ayt.addChar( '7' ); // -> '070 7'
ayt.addChar( '1' ); // -> '070 71'
ayt.addChar( '2' ); // -> '070 712'
ayt.addChar( '3' ); // -> '070 712 3'
ayt.addChar( '4' ); // -> '070 712 34'
ayt.addChar( '5' ); // -> '070 712 34 5'
ayt.addChar( '6' ); // -> '070 712 34 56'
ayt.removeChar( );  // -> '070 712 34 5'
ayt.addChar( '7' ); // -> '070 712 34 57'

awesome-phonenumber's People

Contributors

chris-findlay avatar grantila avatar lgtm-migrator avatar rokoroku avatar ruimarinho avatar tlouisse 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

awesome-phonenumber's Issues

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

False positive brazilian phone number

This phone number 551175757575 is an invalid brazilian phone number, but the method isMobile() is returning true because of its first number 7 after brazilian DDD.
The others phone numbers such as 551185757575 are returning false correctly.

Example code

const PhoneNumber = require( 'awesome-phonenumber' );

const pn = new PhoneNumber( '+551185757575', 'ZZ' );
console.log(pn.isMobile()); // false is ok

const pn2 = new PhoneNumber( '+551175757575', 'ZZ' );
console.log(pn2.isMobile()); // returns true, its wrong, it must return false

AsYouType formatting issues

The As You Type functionality doesn't appear to work as documented in the README.md file. When I execute a removeChar() earlier in the format, the formatting seems to break down. I made the assumption that:

  • .removeChar() would remove any formatting that was inserted AND a phone number digit. Essentially this would be like an "undo". That doesn't seem to be the case, it just removes the last character.
  • I assumed that adding characters after removing characters would continue the formatting but that doesn't appear to be the case.

The following is my Jest test that replicates the README example but with actually passing values.

import PhoneNumber from 'awesome-phonenumber';

describe('PhoneNumber', () => {
  test('#getAsYouType()', () => {
    const ayt = PhoneNumber.getAsYouType('SE');
    expect(ayt.addChar('0')).toEqual('0');
    expect(ayt.addChar('7')).toEqual('07');
    expect(ayt.addChar('0')).toEqual('070');
    expect(ayt.addChar('7')).toEqual('070-7');
    expect(ayt.addChar('1')).toEqual('070-71');
    expect(ayt.addChar('2')).toEqual('070-712');
    expect(ayt.addChar('3')).toEqual('070-712 3');
    expect(ayt.removeChar()).toEqual('070-712 '); // Trailing space not expected
    expect(ayt.removeChar()).toEqual('070-712');
    expect(ayt.addChar('3')).toEqual('070-7123'); // Expected '070-712 3'
    expect(ayt.addChar('4')).toEqual('070-71234');
    expect(ayt.addChar('5')).toEqual('070-712345');
    expect(ayt.addChar('6')).toEqual('070-7123456');
    expect(ayt.removeChar()).toEqual('070-712345');
    expect(ayt.addChar('7')).toEqual('070-7123457');
  });
});

I'm curious if this is a bug or if I'm misinterpreting the expected use of As You Type.

ayt.getPhoneNumber().getNumber() can return undefined while the typing says it will always return a string

I think the typing in lib/index.d.ts should be updated to reflect that this method can return undefined. Currently it is typed saying it will always return a string but the following code will return undefined if there are not at least 2 digits in the phone number:

const PhoneNumber = require("awesome-phonenumber")

const ayt = PhoneNumber.getAsYouType("US")
console.log(ayt.getPhoneNumber().getNumber()) // undefined

ayt.addChar("1") // "1"
ayt.addChar("1") // "11"
console.log(ayt.getPhoneNumber().getNumber()) // "11"

Region code for phone numbers with no fixed country (e.g. +808) are erroneously set to US

Certain phone number country dialing codes are not associated with specific countries, for example, +800, +808, and +870.

The official Java and JavaScript libphonenumber correctly do not set the region code and country code for these phone numbers. However, awesome-phonenumber incorrectly identify these numbers as US phone numbers.

See https://github.com/googlei18n/libphonenumber/blob/master/resources/PhoneNumberMetadata.xml for detailed metadata used in official libraries.

Dynamically load locale?

Even with all the minification, this library is pretty large. It would be cool if there was a way to dynamically load only the stuff needed for a particular locale.

Like for instance, an AsYouTypeFormatter for only english.

TSlint failed

Hi,

I import awesome-phonenumber in my TS code with:

import Phonenumber = require("awesome-phonenumber");

and I get this error from tslint:
[ts] Cannot use 'new' with an expression whose type lacks a call or construct signature.

I found the same error on this page project Fuse:
PR
so I solve It on awesome-phonenumber like this commit.
commit

I remove the error by changing index.d.ts

as:

export as namespace AwesomePhonenumber;
export = PhoneNumber;

declare type PhoneNumberFormat =
	'e164' |
	'international' |
	'national' |
	'rfc3966' |
	'significant';

declare type PhoneNumberTypes =
	'fixed-line' |
	'fixed-line-or-mobile' |
	'mobile' |
	'pager' |
	'personal-number' |
	'premium-rate' |
	'shared-cost' |
	'toll-free' |
	'uan' |
	'voip' |
	'unknown';

declare class PhoneNumber
{
	constructor( phoneNumber: string, countryCode?: string );

	isValid( ): boolean;
	canBeInternationallyDialled( ): boolean;
	isPossible( ): boolean;
	getType( ): PhoneNumberTypes;
	isMobile( ): boolean;
	isFixedLine( ): boolean;
	getNumber( type?: PhoneNumberFormat ): string;
	getNumberFrom( regionCode: string ): string;
	getRegionCode( ): string;
	toJSON( ): any;

	static getCountryCodeForRegionCode( regionCode: string ): number;
	static getRegionCodeForCountryCode( countryCode: number ): string;
	static getSupportedCallingCodes( ): string[ ];
	static getExample( regionCode: string, type?: PhoneNumberTypes ): PhoneNumber;
	static getAsYouType( regionCode: string ): AsYouType;
}

declare class AsYouType
{
	addChar( char: string ): string;
	number( ): string;
	removeChar( ): string;
	reset( number?: string ): string;
	getPhoneNumber( ): PhoneNumber;
}

Custom formatter and other number compoments

Hi,
#1, is it possible to specify the different number formatter?

For example, currently, getNumber('international') for US number returns +1 999-999-9999. I would like to display in ie +1 (999) 999-9999
#2. can it parse number into Area Code or Extension if exist?

Thanks & regards

Update the comparison table

The latest version of google-libphonenumber is 1.0.7, the comparison in README seems a little bit old.
I am wondering anything has changed.

It would be great if a benchmark script could be added, so others could try and see the difference on their machines.

Get the exact part of input on which phone was guessed

I try to parse mingled phone number out of text.

var pn = new PhoneNumber( 'very important asdf for  070712345 6', 'SE' );
//note the space before last number

The lib guesses the phone correctly
e164: "+46707123456"
but how can i get the basis string ("070712345 6") that lib took for parsing?
(not the whole text)

Metadata uptodate?

Hi,

I am having a trouble with some numbers, e.g. +1613 734.6759, which returns US as region instead of CA, whereas the "original" google returns the correct region code (CA). (google-libphonenumber returns the correct region code :-) ).

Any idea why this is wrong?

Thanks,
-Stephane

Get region code requiring more digits that it should

function extractRegionCode( phoneNumber )
{
if ( phoneNumber.charAt( 0 ) !== '+' || phoneNumber.length < 5 )
return null;
var firstOne = phoneNumber.substr( 1, 1 );
var firstTwo = phoneNumber.substr( 1, 2 );
var firstThree = phoneNumber.substr( 1, 3 );
var regionCode;
regionCode = PhoneNumber.getRegionCodeForCountryCode( firstOne );
if ( regionCode !== 'ZZ' )
return regionCode;
regionCode = PhoneNumber.getRegionCodeForCountryCode( firstTwo );
if ( regionCode !== 'ZZ' )
return regionCode;
regionCode = PhoneNumber.getRegionCodeForCountryCode( firstThree );
if ( regionCode !== 'ZZ' )
return regionCode;
return null;
}

As we can see on that snippet, to get the region code we need to write 4 digits but it's only taking into account the first 3, can we switch it to just 3?

Bugs

Hello,
I tested your API and I found that when I make a request like this
var body = new AwsomePhone( "0652648569xx", "FR");
or with that number
065254(6569xx
065254(6569]xx
I got this

{
  "number": {
    "input": "0652546569xx",
    "international": "+33 6 52 54 65 69",
    "national": "06 52 54 65 69",
    "e164": "+33652546569",
    "rfc3966": "tel:+33-6-52-54-65-69",
    "significant": "652546569"
  },
  "regionCode": "FR",
  "valid": true,
  "possible": true,
  "type": "mobile",
  "possibility": "is-possible"
}

Best regards

`getSupportedCallingCodes` insufficient due to not being unique

libPhoneNumber has both getSupportedCallingCodes and getSupportedRegions - the latter being suitable for a country selector as all its 246 entries are unique, unlike the 224 entries from the former.

It'd be really nice to expose both functions, as the missing one is more useful in my case, since pn.getSupportedCallingCodes().map(x => pn.getRegionCodeForCountryCode(x)) is both incomplete and not entirely ISOAlpha2 - there are several 001 entries in there too.

Returning 001 in region code

While I was getting region code for mobile number +979998889998, the Api is returning region code 001 in response in Number type.
I was expecting a string of region code.

Declaring valid number as invalid

Hi,

When validating any number that starts with 085 in the ZA region, these numbers are marked as invalid, however, these numbers are valid.

Any reason for this?

Mobile french phone number in "070..." to "072..." are not valid

Hello,
A typical french mobile phone number starts with 06 or 07 and has 10 digits.
I noticed though that awesome-phonenumber believes that phone numbers with 10 digits that start with "070", "071" or "072" are not valid. I'm not sure why that is.
Is there an actual official rule in the french phone system that make these numbers invalid, or is it an error in awesome-phonenumber ?

Example :

import PhoneNumber from 'awesome-phonenumber';
const pn1 = new PhoneNumber("0710000000", "FR");
console.log(JSON.stringify(pn1.toJSON()));
// This one is not valid :
// {
//   "number": {
//     "input": "0710000000",
//     "international": "+33 7 10 00 00 00",
//     "national": "07 10 00 00 00",
//     "e164": "+33710000000",
//     "rfc3966": "tel:+33-7-10-00-00-00",
//     "significant": "710000000"
//   },
//   "regionCode": "FR",
//   "valid": false,
//   "possible": true,
//   "canBeInternationallyDialled": true,
//   "type": "unknown",
//   "possibility": "is-possible"
// }
const pn2 = new PhoneNumber("0730000000", "FR");
console.log(JSON.stringify(pn2.toJSON()));
// While this one is :
// {
//   "number": {
//     "input": "0730000000",
//     "international": "+33 7 30 00 00 00",
//     "national": "07 30 00 00 00",
//     "e164": "+33730000000",
//     "rfc3966": "tel:+33-7-30-00-00-00",
//     "significant": "730000000"
//   },
//   "regionCode": "FR",
//   "valid": true,
//   "possible": true,
//   "canBeInternationallyDialled": true,
//   "type": "mobile",
//   "possibility": "is-possible"
// }

Thanks in advance !

getExample returns the same number per region

Hi,

Every time when I call getExample I obtain the same phone number. I thought that this will be randomized, or at least, the same sequence of different numbers. Are those examples hardcoded?

var PhoneNumber=require("awesome-phonenumber");

console.log(PhoneNumber.getExample("PL").getNumber());
console.log(PhoneNumber.getExample("PL").getNumber());
console.log(PhoneNumber.getExample("PL").getNumber());
console.log(PhoneNumber.getExample("SE").getNumber());
console.log(PhoneNumber.getExample("SE").getNumber());
console.log(PhoneNumber.getExample("PL").getNumber());
+48123456789
+48123456789
+48123456789
+468123456
+468123456
+48123456789

Fatal error occurs when phone number is NULL when using getNumber function

In order to gracefully handle conditions where the phone number passed into the module is a NULL OR numeric value, the returned response/result should probably be NULL.

Currently, the following fatal error is returned (extremely problematic in code with no error handling):

TypeError: Cannot read property 'charAt' of null
at new Y (...\awesome-phonenumber\lib\index.js:481:146)

It's better to have the result of this condition be NULL and not perform the charAt enumeration or other evaluation of user input. Furthermore, in most cases, the result of null expressions usually result in null responses/result.

Sometimes it is not always possible for developers to anticipate or perform pre-validation of all input from end users, in this case phone numbers, including null or empty values.

UPDATE:
The following also produces the same error!

 var pn = new PhoneNumber('(229) 596-4236', 'US');
 console.log(pn.getNumber('significant'));

New phone numbers in nigeria region is not being validated

Hello, I am using awesome-phonenumber in my current project and validating phone numbers with this plugin

but nowadays I am facing issues after new phone number series is introduced in a particular region.

not valid phone number ex: +234801*****54, I have tried updating the package to the latest version.

"awesome-phonenumber": "^2.24.0",
Code Snapshot:

static phnValidate(c: FormControl): ValidationErrors { const num = c.value; let isValid = false; const pn = new awesomePhonenumber(num != null ? num : '+91'); if (pn.isValid() && pn.isMobile()) { isValid = true } const message = { 'phoneNumber': { 'message': 'Phone Number is not valid' } }; return isValid ? null : message; }
Error screenshot:

image

Valid phone number screenshot:
image

Stand alone version

Is there any stand alone version available that can be used without many other dependencies???

Update to 8.7.0

Could you update the library to 8.7.0?
It has several fixes in validations.
Thanks!

CN phone number is invalid

hey, so how this is possible that CN number is invalid? The piece of response while debugging value of the number with this package:

{...
regionCode: 'CN',
valid: false,
possible: true,
canBeInternationallyDialled: true,
type: 'unknown',
possibility: 'is-possible'
...}

Feature request - easily get IDC

Hi,

It would be nice if there were an easy way to get the ICD (international dialing code) from the number.

Currently, I have to do this:

pn.getNumber('international').split(' ')[0].replace(/^\+/, '')

Would be nice to have that available:

pn.getNumber('idc')

Update?

Hey can you update the lib?

And can you create a build howto, what deps need etc?

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Unable to use API functions

I created a bunch of util functions as wrappers to your library but for some reason, they're not working.

The behavior I'm getting while using AsYouType is that after entering the second digit, I get undefined but interestingly it's formatted like a US phone number -- and I'm entering a US phone number. Here's what it looks like:
capture

I'm having problems with other wrapper functions as well. Clearly, I'm making a mistake somehwere.

Here's what my util functions looks like:

let PhoneNumber = require('awesome-phonenumber');

export const formatPhoneNumberAsYouType = (input, countryId) => {
    
    const output = new PhoneNumber.getAsYouType(countryId.toUpperCase());
    output.addChar(input);

    return output.number();
}

export const unformatPhoneNumber = (input, countryId) => {

    const pn = new PhoneNumber(input, countryId.toUpperCase());

    return pn.getPhoneNumber('significant');
}

What am I doing wrong here?

Wrong recognition of region code

Currently the region code recognition, takes into account the first 4 digits, as minimum as possible, in order to try to figure out the region code. This is problematic for shared region codes such as 1, that is used both for US and Canada. This means that currently, no Canadian number is recognized as such, unless an explicit country code is passed.

Update lib to 8.10.1

Hi there,

Is there any chance, this lib can be updated to 8.10.1 please? I can open up a pull request as well, if there's a guide I can follow.

Thanks

Question about managing number of digits in phone number

Hi,

This is not really an issue but a question. I see that there are API methods that indicate whether a number is too short or too long. I suspect this is because not every country in the world necessarily has a fixed number of digits in its phone numbers. Is that the case?

What's the best way to use this library to disallow extra digits as the user enters numbers. For example, in the U.S, it's always 3 digits for the area code and 7 digits for the number, a total of 10 digits -- without separating characters. I want to prevent the user from entering more than 10 digits. Do I check for both too long and too short as the user types in the number?

Thanks,
Sam

Question: protobuf?

I note that the output appears to include the Protobuf part of the closure runtime lib (or at least it's header comment). Do you know if this tree-shakes out?

Should always validate phone number format

const PN = require('awesome-phonenumber');
const { PhoneNumberUtil } = require('google-libphonenumber');

const awesomepn = new PN('+1613 734.6759');
console.log(awesomepn.getRegionCode()); // CA

const awesomepn2 = new PN('+1613 734.6759', 'US');
console.log(awesomepn2.getRegionCode()); // US

// `google-libphonenumber` always retrieves Region Code from a Country Code included phone number by checking its' format pattern.
// So the above issue never gonna happen even if you pass in a wrong region code.
const pnu = PhoneNumberUtil.getInstance();
console.log(pnu.getRegionCodeForNumber(pnu.parse('+1613 734.6759', 'US'))); // CA

Missing isValidForRegion()

When i try to validated e164 formatted number with typo in the prefix, I got some weird results.

eg:

  • Given a valid french mobile number: +33 6 12 34 56 78
  • Say there is a typo in prefix (missing 3): +3 6 12 34 56 78

No matter I pass the correct region in the constructor, the number is still valid (but with a Hungarian prefix):

new PhoneNumber("+3 6 12 34 56 78").isValid(); // true
new PhoneNumber("+3 6 12 34 56 78", "FR").isValid(); // true
new PhoneNumber("+3 6 12 34 56 78", "FR").getNumber(); // +3612345678
new PhoneNumber("+3 6 12 34 56 78", "FR").getNumber('national'); // (06 1) 234 5678
new PhoneNumber("+3 6 12 34 56 78", "FR").getRegionCode(); // HU

But as I can be seen here the function isValidNumberForRegion() returns false.

If it were possible to add this function or any check in an instance if region is given to this (awesome ^^) lib, that would be great.

I'm not sure I can do it myself, but I was thinking something like:

function isValidNumberForRegion(regionCode) {
  if(this.getRegionCode() !== regionCode) return false;
  return true;
}

Honestly it's my first time digging into a lib's code, I'm a bit confused.

Big Bug

const PhoneNumber = require( 'awesome-phonenumber' );

const pn = new PhoneNumber( '+237697644414', 'SE' );
console.log(pn.isValid()) // return true it's not correct +237697644414 is a Cameroonian number

CountryCodes for some countries are wrong

console.log(PhoneNumber.getExample('AG').getNumber()); // e.g. +12684601234
console.log(PhoneNumber.getExample('AG').getCountryCode()); // 1

but it should be 1268
for Jamaika, it should be 1876
there are several others.

also, extracting the countryCode doesn't work with those countries.

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.