awesome-phonenumber vs google-libphonenumber vs libphonenumber-js vs phone vs phone-formatter vs validator
Phone Number Validation and Formatting
awesome-phonenumbergoogle-libphonenumberlibphonenumber-jsphonephone-formattervalidatorSimilar Packages:

Phone Number Validation and Formatting

Phone number validation and formatting libraries in JavaScript help developers ensure that phone numbers entered by users are valid, correctly formatted, and standardized according to international or local conventions. These libraries provide tools for parsing, validating, and formatting phone numbers, which can be particularly useful for applications that require accurate contact information, such as e-commerce platforms, CRM systems, and communication apps. They help improve data quality, enhance user experience, and ensure consistency across different systems. awesome-phonenumber is a comprehensive library for parsing, validating, and formatting phone numbers with support for multiple formats and internationalization. google-libphonenumber is a JavaScript port of Google's libphonenumber library, offering extensive phone number validation, formatting, and parsing capabilities based on Google's data. libphonenumber-js is a lightweight alternative to google-libphonenumber, providing essential phone number validation and formatting features with a smaller footprint. phone is a simple library for validating and formatting phone numbers, focusing on ease of use and minimal configuration. phone-formatter is a lightweight library for formatting phone numbers according to various international and local formats, with a focus on simplicity and performance. validator is a comprehensive validation library that includes a wide range of validators, including phone number validation, but is not specialized in phone number handling.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
awesome-phonenumber0707734 kB16a month agoMIT
google-libphonenumber01,479618 kB302 months ago(MIT AND Apache-2.0)
libphonenumber-js0-8.77 MB-4 days agoMIT
phone091788 kB1a month agoMIT
phone-formatter046-4--
validator023,754817 kB3733 months agoMIT

Feature Comparison: awesome-phonenumber vs google-libphonenumber vs libphonenumber-js vs phone vs phone-formatter vs validator

Validation Accuracy

  • awesome-phonenumber:

    awesome-phonenumber provides accurate validation based on international standards, with support for multiple formats and country-specific rules. It allows for customization and provides detailed validation results, making it suitable for applications that require precise validation.

  • google-libphonenumber:

    google-libphonenumber offers the most accurate validation based on Google's extensive data and algorithms. It supports a wide range of countries and formats, making it the gold standard for phone number validation. It is particularly reliable for applications that need to validate numbers from multiple countries.

  • libphonenumber-js:

    libphonenumber-js provides accurate validation using a subset of Google's libphonenumber data. While it is not as comprehensive as google-libphonenumber, it offers reliable validation for most common use cases, especially for applications that prioritize performance and smaller bundle sizes.

  • phone:

    phone provides basic validation based on country codes and simple rules. It is suitable for applications that need quick validation without extensive checks, but it may not be as thorough as specialized libraries.

  • phone-formatter:

    phone-formatter focuses on formatting rather than validation. It provides basic validation to ensure numbers are in a valid format before formatting, but it is not designed for comprehensive validation.

  • validator:

    validator includes a simple phone number validation function that checks for valid formats based on regular expressions. It is not specialized in phone number validation but can be useful for basic checks within a broader validation context.

Formatting Capabilities

  • awesome-phonenumber:

    awesome-phonenumber offers extensive formatting capabilities, including support for international, national, and E.164 formats. It allows for customization of formatting styles and can handle multiple formats within a single application.

  • google-libphonenumber:

    google-libphonenumber provides comprehensive formatting options based on Google's libphonenumber data. It supports international, national, and E.164 formats, as well as custom formatting based on country-specific rules. It is ideal for applications that need consistent and accurate formatting across multiple countries.

  • libphonenumber-js:

    libphonenumber-js offers essential formatting features with support for international and national formats. It is a lightweight alternative that provides quick formatting while maintaining accuracy, making it suitable for applications that need fast and reliable formatting without the overhead of a larger library.

  • phone:

    phone provides basic formatting capabilities based on country codes. It is simple to use and allows for quick formatting of phone numbers, but it may not support advanced or customizable formatting styles.

  • phone-formatter:

    phone-formatter specializes in formatting phone numbers according to various international and local formats. It is lightweight and easy to use, making it ideal for applications that need fast and accurate formatting without extensive configuration.

  • validator:

    validator does not provide formatting capabilities for phone numbers. It is primarily a validation library and does not include features for formatting or manipulating phone number data.

Internationalization

  • awesome-phonenumber:

    awesome-phonenumber supports internationalization with built-in data for multiple countries. It allows for easy handling of phone numbers from different regions and provides tools for validating and formatting numbers based on country-specific rules. It is suitable for applications that need to handle international phone numbers seamlessly.

  • google-libphonenumber:

    google-libphonenumber is designed for internationalization, with comprehensive data for phone numbers from around the world. It supports validation and formatting for a wide range of countries, making it ideal for applications that operate globally and need to handle phone numbers from multiple regions.

  • libphonenumber-js:

    libphonenumber-js supports internationalization with a focus on providing essential data for multiple countries. It is a lightweight option for applications that need to handle international phone numbers without the overhead of a full-featured library.

  • phone:

    phone supports international phone numbers by allowing validation and formatting based on country codes. It is simple to use for international numbers but may lack advanced features for handling complex internationalization scenarios.

  • phone-formatter:

    phone-formatter supports internationalization by providing formatting rules for multiple countries. It is designed to handle international phone numbers and format them correctly based on the specified country or region.

  • validator:

    validator does not have specialized support for internationalization of phone numbers. Its phone number validation is based on general patterns and does not account for country-specific rules or formats.

Ease of Use

  • awesome-phonenumber:

    awesome-phonenumber provides a user-friendly API with clear documentation. It is easy to integrate and use for both simple and advanced phone number handling tasks. The library's flexibility and comprehensive features make it accessible to developers of all skill levels.

  • google-libphonenumber:

    google-libphonenumber has a well-documented API but can be complex due to its extensive features. It may require some time to fully understand and utilize all its capabilities, especially for developers new to phone number validation.

  • libphonenumber-js:

    libphonenumber-js offers a simpler API compared to google-libphonenumber, making it easier to use for basic validation and formatting tasks. Its lightweight nature and clear documentation make it a good choice for developers looking for a quick and efficient solution.

  • phone:

    phone is designed for simplicity and ease of use. It has a straightforward API that allows for quick validation and formatting of phone numbers with minimal configuration.

  • phone-formatter:

    phone-formatter is easy to use, with a simple API for formatting phone numbers. It is well-documented and designed for quick integration into applications.

  • validator:

    validator is easy to use for basic validation tasks, including phone number validation. Its API is straightforward, and it provides clear documentation for all its validation functions.

Ease of Use: Code Examples

  • awesome-phonenumber:

    awesome-phonenumber example

    import PhoneNumber from 'awesome-phonenumber';
    const pn = new PhoneNumber('+14155552671');
    console.log(pn.isValid()); // true
    console.log(pn.getNumber()); // +14155552671
    console.log(pn.getNumber('national')); // (415) 555-2671
    
  • google-libphonenumber:

    google-libphonenumber example

    import { PhoneNumberUtil } from 'google-libphonenumber';
    const phoneUtil = PhoneNumberUtil.getInstance();
    const number = phoneUtil.parse('+14155552671');
    console.log(phoneUtil.isValidNumber(number)); // true
    console.log(phoneUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.NATIONAL)); // (415) 555-2671
    
  • libphonenumber-js:

    libphonenumber-js example

    import { parsePhoneNumberFromString } from 'libphonenumber-js';
    const phoneNumber = parsePhoneNumberFromString('+14155552671');
    console.log(phoneNumber.isValid()); // true
    console.log(phoneNumber.formatNational()); // (415) 555-2671
    
  • phone:

    phone example

    import { phone } from 'phone';
    const { isValid, phoneNumber } = phone('+14155552671');
    console.log(isValid); // true
    console.log(phoneNumber); // +14155552671
    
  • phone-formatter:

    phone-formatter example

    import { formatPhoneNumber } from 'phone-formatter';
    const formattedNumber = formatPhoneNumber('4155552671', 'US');
    console.log(formattedNumber); // (415) 555-2671
    
  • validator:

    validator example

    import validator from 'validator';
    const isValidPhone = validator.isMobilePhone('+14155552671', 'en-US');
    console.log(isValidPhone); // true
    

How to Choose: awesome-phonenumber vs google-libphonenumber vs libphonenumber-js vs phone vs phone-formatter vs validator

  • awesome-phonenumber:

    Choose awesome-phonenumber if you need a comprehensive solution for phone number validation and formatting that supports multiple formats and internationalization. It is particularly useful for applications that require detailed phone number handling and customization.

  • google-libphonenumber:

    Choose google-libphonenumber if you require the most accurate and reliable phone number validation and formatting based on Google's extensive data. It is ideal for applications that need robust validation and support for a wide range of countries and formats.

  • libphonenumber-js:

    Choose libphonenumber-js if you need a lightweight alternative to google-libphonenumber that provides essential validation and formatting features with a smaller bundle size. It is suitable for performance-sensitive applications that still require accurate phone number handling.

  • phone:

    Choose phone if you need a simple and easy-to-use library for basic phone number validation and formatting. It is ideal for applications that require minimal configuration and straightforward functionality.

  • phone-formatter:

    Choose phone-formatter if your primary need is to format phone numbers according to various international and local formats. It is lightweight and focuses on performance, making it suitable for applications that need fast formatting without extensive validation.

  • validator:

    Choose validator if you need a comprehensive validation library that includes phone number validation along with other types of validations (e.g., email, URL, credit card). It is useful for applications that require multiple types of input validation but do not need specialized phone number handling.

README for awesome-phonenumber

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.

Unlike libphonenumber, it includes a findNumbers( ) function to find phone numbers in text.

TypeScript typings are provided within the package.

Uses libphonenumber v9.0.24

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
  • v7:
    • Added findNumbers( ) feature, to find phone numbers in text
    • Added support for short numbers

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.

Actionawesome-phonenumber
7.2.0
(lib 8.13.47)
google-libphonenumber
3.2.38
(lib 8.13.42)
libphonenumber-js
1.11.9
(lib -)
Load library first time7.82 ms ✅14.28 ms14.53 ms
Parse first phone number2.00 ms1.86 ms1.65 ms ✅
⇒ Load + parse first number9.82 ms ✅16.14 ms16.18 ms
Format again0.09 ms ✅0.22 ms0.13 ms
Parse again0.39 ms ✅0.51 ms0.43 ms
Increased memory usage9.77 M ✅12.71 M11.25 M
node_modules size720 K* 604 K ✅9.9 M
node_modules files9* 7 ✅787

* NOTE: google-libphonenumber only ships CJS, while awesome-phonenumber and libphonenumber-js ships both CJS and ESM

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,
	shortPossible: false,
	shortValid: false,
	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;
	shortPossible: boolean;
	shortValid: 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';
	shortPossible: boolean;
	shortValid: boolean;
	error?: unknown;
};

Note that an incorrect (invalid) phone number can still be a valid short number for the given region.

API

import {
	parsePhoneNumber,
	findNumbers,
	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.

findNumbers

To find (extract) phone numbers in text, use findNumbers( ):

import { findNumbers } from 'awesome-phonenumber'

const text = 'My number is +46 707 123 456, otherwise call +33777777777.';
const numbers = findNumbers( text );

The returned list of numbers is of the type PhoneNumberMatch such as:

interface PhoneNumberMatch
{
	text: string; // The raw string found
	phoneNumber: object; // Same as the result of parsePhoneNumber()
	start: number; // Start offset in the text
	end: number; // End offset in the text
}

A second options argument to findNumbers( text, options ) can be provided on the form:

interface FindNumbersOptions
{
	defaultRegionCode?: string;
	leniency?: FindNumbersLeniency;
	maxTries?: number;
}

where FindNumbersLeniency is an enum of 'valid' or 'possible'. The default is 'valid' meaning that only valid phone numbers are found. If this is set to 'possible' also possible (but invalid) phone numbers are found.

defaultRegionCode can be set (e.g. to 'SE' for Sweden), in which case phone numbers on national form (i.e. without + prefix) will be found, as long as they are from that region.

For really large texts, maxTries will set the maximum number of phone numbers to try to find (not necessary actually find).

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'