Convert Figma logo to code with AI

google logolibphonenumber

Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.

16,442
2,036
16,442
110

Top Related Projects

Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.

PHP version of Google's phone number handling library

Python port of Google's libphonenumber

A Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.

Quick Overview

Google's libphonenumber is an open-source library for parsing, formatting, and validating international phone numbers. It provides a comprehensive set of tools for working with phone numbers, including support for a wide range of countries and regions, as well as advanced features like phone number geocoding and phone number formatting.

Pros

  • Comprehensive Phone Number Support: libphonenumber supports phone numbers from over 200 regions and countries, making it a robust and versatile solution for international phone number handling.
  • Accurate Phone Number Validation: The library uses a large, regularly updated database of phone number metadata to provide accurate validation and formatting of phone numbers.
  • Extensive Functionality: In addition to basic parsing and formatting, libphonenumber offers advanced features like phone number geocoding, phone number formatting, and phone number normalization.
  • Active Development and Community: The project is actively maintained by Google and has a large, engaged community of contributors, ensuring ongoing improvements and bug fixes.

Cons

  • Complexity: The library's comprehensive feature set and support for a wide range of phone number formats can make it more complex to integrate and use, especially for simple use cases.
  • Performance: Depending on the size of the phone number dataset and the complexity of the operations, the library's performance may not be optimal for high-volume, real-time applications.
  • Language Support: While libphonenumber supports a wide range of languages, it may not provide the same level of localization and internationalization as some other phone number libraries.
  • Licensing: The library is licensed under the Apache License, Version 2.0, which may not be compatible with all project requirements.

Code Examples

Here are a few examples of how to use the libphonenumber library in different programming languages:

JavaScript

const libphonenumber = require('google-libphonenumber');
const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();

// Parse a phone number
const phoneNumber = phoneUtil.parse('+1 650-253-0000', 'US');

// Validate a phone number
const isValid = phoneUtil.isValidNumber(phoneNumber);

// Format a phone number
const formattedNumber = phoneUtil.format(phoneNumber, libphonenumber.PhoneNumberFormat.INTERNATIONAL);

Python

from phonenumbers import parse, is_valid_number, format_number, PhoneNumberFormat

# Parse a phone number
phone_number = parse('+1 650-253-0000', 'US')

# Validate a phone number
is_valid = is_valid_number(phone_number)

# Format a phone number
formatted_number = format_number(phone_number, PhoneNumberFormat.INTERNATIONAL)

Java

import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;

// Parse a phone number
PhoneNumber phoneNumber = PhoneNumberUtil.getInstance().parse("+1 650-253-0000", "US");

// Validate a phone number
boolean isValid = PhoneNumberUtil.getInstance().isValidNumber(phoneNumber);

// Format a phone number
String formattedNumber = PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);

Getting Started

To get started with the libphonenumber library, follow these steps:

  1. Install the library in your project. The installation process varies depending on the programming language and package manager you're using. For example, in JavaScript, you can install the library using npm:

    npm install google-libphonenumber
    
  2. Import the necessary modules or classes from the library. The import syntax will depend on the programming language you're using. For example, in JavaScript:

    const libphonenumber = require('google-libphonenumber');
    const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
    
  3. Use the library's functions to parse, validate, and format phone numbers. The specific function calls will depend on the task you're trying to accomplish. For example, to parse a phone number in JavaScript:

    const phoneNumber = phoneUtil.parse('+1 650
    

Competitor Comparisons

Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.

Pros of libphonenumber

  • Comprehensive phone number parsing and formatting capabilities
  • Support for a wide range of countries and regions
  • Actively maintained and regularly updated

Cons of libphonenumber

  • Larger codebase and dependencies compared to the alternative
  • May be overkill for simple phone number validation use cases

Code Comparison

libphonenumber:

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber swissNumberProto = phoneUtil.parse("+41 44 668 18 00", "CH");
boolean isValid = phoneUtil.isValidNumber(swissNumberProto);

libphonenumber:

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber swissNumberProto = phoneUtil.parse("+41 44 668 18 00", "CH");
boolean isValid = phoneUtil.isValidNumber(swissNumberProto);

As you can see, the code for both repositories is nearly identical, as they are the same project.

PHP version of Google's phone number handling library

Pros of libphonenumber-for-php

  • Easier Installation: libphonenumber-for-php can be easily installed via Composer, making it more accessible for PHP developers.
  • Actively Maintained: The libphonenumber-for-php project is actively maintained, with regular updates and bug fixes.
  • Supports Newer PHP Versions: libphonenumber-for-php supports newer versions of PHP, including PHP 8.x, which is important for modern web development.

Cons of libphonenumber-for-php

  • Fewer Features: Compared to the original libphonenumber, the PHP version may have fewer features and capabilities.
  • Potential Compatibility Issues: There may be some compatibility issues between the PHP version and the original libphonenumber, which could lead to differences in behavior or functionality.
  • Smaller Community: The libphonenumber-for-php project has a smaller community compared to the original libphonenumber, which could mean fewer resources and support available.

Code Comparison

Here's a brief code comparison between the two projects:

Google's libphonenumber:

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber swissNumberProto = phoneUtil.parse("+41 44 668 18 00", "CH");
boolean isValid = phoneUtil.isValidNumber(swissNumberProto);

libphonenumber-for-php:

$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
$swissNumberProto = $phoneUtil->parse('+41 44 668 18 00', 'CH');
$isValid = $phoneUtil->isValidNumber($swissNumberProto);

As you can see, the overall structure and usage of the two libraries is quite similar, with the main difference being the language-specific syntax (Java vs. PHP).

Python port of Google's libphonenumber

Pros of python-phonenumbers

  • Pythonic API: The python-phonenumbers library provides a more Pythonic API compared to the Google libphonenumber, making it easier to integrate into Python-based projects.
  • Simplified Dependencies: python-phonenumbers has fewer dependencies compared to the Google library, which can be beneficial for projects with strict dependency requirements.
  • Active Maintenance: The python-phonenumbers project appears to have more active maintenance and development compared to the Google libphonenumber project.

Cons of python-phonenumbers

  • Limited Functionality: The python-phonenumbers library may not have the same level of comprehensive functionality as the Google libphonenumber, which is the original and more feature-rich library.
  • Potential Compatibility Issues: Since python-phonenumbers is a separate implementation, there may be some compatibility issues or differences in behavior compared to the Google libphonenumber.

Code Comparison

Google libphonenumber (Java):

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber swissNumber = phoneUtil.parse("+41 44 668 18 00", "CH");
boolean isValid = phoneUtil.isValidNumber(swissNumber);

python-phonenumbers (Python):

from phonenumbers import parse, is_valid_number
swiss_number = parse("+41 44 668 18 00", "CH")
is_valid = is_valid_number(swiss_number)

The code snippets demonstrate the similar functionality between the two libraries, with the python-phonenumbers version providing a more concise and Pythonic API.

A Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.

Pros of PhoneNumberKit

  • Smaller Footprint: PhoneNumberKit is a lightweight library, with a smaller footprint compared to libphonenumber, making it more suitable for mobile applications.
  • Swift-first Approach: PhoneNumberKit is written in Swift, providing a more idiomatic and native experience for Swift developers.
  • Easier Integration: PhoneNumberKit has a simpler API and requires less configuration, making it easier to integrate into iOS projects.

Cons of PhoneNumberKit

  • Limited Functionality: PhoneNumberKit has a more limited set of features compared to libphonenumber, such as fewer supported countries and less comprehensive validation.
  • Potential Accuracy Issues: Due to its smaller codebase, PhoneNumberKit may not be as accurate as libphonenumber in certain edge cases or for less common phone number formats.
  • Fewer Contributions: libphonenumber has a larger and more active community, with more contributors and a more extensive set of features and bug fixes.

Code Comparison

libphonenumber (Java):

PhoneNumber phoneNumber = phoneUtil.parse("+1 650-253-0000", "US");
boolean isValid = phoneUtil.isValidNumber(phoneNumber);

PhoneNumberKit (Swift):

let phoneNumber = try? PhoneNumber(rawNumber: "+1 650-253-0000", region: "US")
let isValid = phoneNumber?.isValid ?? false

The libphonenumber code is more verbose, requiring the use of a PhoneUtil object and explicit parsing and validation steps. In contrast, the PhoneNumberKit code is more concise, with a simpler API that allows for direct creation and validation of phone numbers.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

What is it?

Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers. The Java version is optimized for running on smartphones, and is used by the Android framework since 4.0 (Ice Cream Sandwich).

Quick links

Highlights of functionality

  • Parsing, formatting, and validating phone numbers for all countries/regions of the world.
  • getNumberType - gets the type of the number based on the number itself; able to distinguish Fixed-line, Mobile, Toll-free, Premium Rate, Shared Cost, VoIP, Personal Numbers, UAN, Pager, and Voicemail (whenever feasible).
  • isNumberMatch - gets a confidence level on whether two numbers could be the same.
  • getExampleNumber and getExampleNumberForType - provide valid example numbers for all countries/regions, with the option of specifying which type of example phone number is needed.
  • isPossibleNumber - quickly guesses whether a number is a possible phone number by using only the length information, much faster than a full validation.
  • isValidNumber - full validation of a phone number for a region using length and prefix information.
  • AsYouTypeFormatter - formats phone numbers on-the-fly when users enter each digit.
  • findNumbers - finds numbers in text.
  • 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.

Demo

Java

The Java demo is updated with a slight delay after the GitHub release.

Last demo update: v8.13.45.

Note: Even though the library (main branch/maven release) is at v8.12.57, because of some deployment issues, we were unable to update the Java demo with the new binary version. We will soon fix this. Meantime, please use JS demo.

If this number is lower than the latest release's version number, we are between releases and the demo may be at either version.

Demo App

There is a demo Android App called E.164 Formatter in this repository. The purpose of this App is to show an example of how the library can be used in a real-life situation, in this case specifically in an Android App using Java.

JavaScript

The JavaScript demo may be run at various tags; this link will take you to master.

Java code

To include the Java code in your application, either integrate with Maven (see wiki) or download the latest jars from the Maven repository.

Javadoc

Javadoc is automatically updated to reflect the latest release at https://javadoc.io/doc/com.googlecode.libphonenumber/libphonenumber/.

Versioning and Announcements

We generally choose the release number following these guidelines.

If any of the changes pushed to master since the last release are incompatible with the intent / specification of an existing libphonenumber API or may cause libphonenumber (Java, C++, or JS) clients to have to change their code to keep building, we publish a major release. For example, if the last release were 7.7.3, the new one would be 8.0.0.

If any of those changes enable clients to update their code to take advantage of new functionality, and if clients would have to roll-back these changes in the event that the release was marked as "bad", we publish a minor release. For example, we'd go from 7.7.3 to 7.8.0.

Otherwise, including when a release contains only metadata changes, we publish a sub-minor release, e.g. 7.7.3 to 7.7.4.

Sometimes we make internal changes to the code or metadata that, while not affecting compatibility for clients, could affect compatibility for porters of the library. For such changes we make announcements to libphonenumber-discuss. Such changes are not reflected in the version number, and we would publish a sub-minor release if there were no other changes.

Want to get notified of new releases? During most of the year, excepting holidays and extenuating circumstances, we release fortnightly. We update release tags and document detailed release notes. We also send an announcement to libphonenumber-discuss for every release.

Quick Examples

Let's say you have a string representing a phone number from Switzerland. This is how you parse/normalize it into a PhoneNumber object:

String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
  PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} catch (NumberParseException e) {
  System.err.println("NumberParseException was thrown: " + e.toString());
}

At this point, swissNumberProto contains:

{
  "country_code": 41,
  "national_number": 446681800
}

PhoneNumber is a class that was originally auto-generated from phonenumber.proto with necessary modifications for efficiency. For details on the meaning of each field, refer to resources/phonenumber.proto.

Now let us validate whether the number is valid:

boolean isValid = phoneUtil.isValidNumber(swissNumberProto); // returns true

There are a few formats supported by the formatting method, as illustrated below:

// Produces "+41 44 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL));
// Produces "044 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL));
// Produces "+41446681800"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164));

You could also choose to format the number in the way it is dialed from another country:

// Produces "011 41 44 668 1800", the number when it is dialed in the United States.
System.out.println(phoneUtil.formatOutOfCountryCallingNumber(swissNumberProto, "US"));

Formatting Phone Numbers 'as you type'

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
AsYouTypeFormatter formatter = phoneUtil.getAsYouTypeFormatter("US");
System.out.println(formatter.inputDigit('6'));  // Outputs "6"
...  // Input more digits
System.out.println(formatter.inputDigit('3'));  // Now outputs "650 253"

Geocoding Phone Numbers

PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance();
// Outputs "Zurich"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.ENGLISH));
// Outputs "Zürich"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.GERMAN));
// Outputs "Zurigo"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.ITALIAN));

Mapping Phone Numbers to original carriers

Caveat: We do not provide data about the current carrier of a phone number, only the original carrier who is assigned the corresponding range. Read about number portability.

PhoneNumber swissMobileNumber =
    new PhoneNumber().setCountryCode(41).setNationalNumber(798765432L);
PhoneNumberToCarrierMapper carrierMapper = PhoneNumberToCarrierMapper.getInstance();
// Outputs "Swisscom"
System.out.println(carrierMapper.getNameForNumber(swissMobileNumber, Locale.ENGLISH));

More examples on how to use the library can be found in the unit tests.

Third-party Ports

Several third-party ports of the phone number library are known to us. We share them here in case they're useful for developers.

However, we emphasize that these ports are by developers outside the libphonenumber project. We do not evaluate their quality or influence their maintenance processes.

Alternatives to our own versions:

  • Android-optimized: Our Java version loads the metadata from Class#getResourcesAsStream and asks that Android apps follow the Android loading best practices of repackaging the metadata and loading from AssetManager#open() themselves (FAQ). If you don't want to do this, check out the port at https://github.com/MichaelRocks/libphonenumber-android, which does repackage the metadata and use AssetManager#open(), and may be depended on without needing those specific loading optimizations from clients. You should also check out the port at https://github.com/lionscribe/libphonenumber-android which also supports geocoding, and only requires a one line code change.
  • Javascript: If you don't want to use our version, which depends on Closure, there are several other options, including https://github.com/catamphetamine/libphonenumber-js - a stripped-down rewrite, about 110 KB in size - and https://github.com/seegno/google-libphonenumber - a browserify-compatible wrapper around the original unmodified library installable via npm, which packs the Google Closure library, about 420 KB in size.

Tools based on libphonenumber metadata:

NPM DownloadsLast 30 Days