Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java phone number format API

Tags:

java

I have a database with millions of phone numbers with free-for-all formatting. Ie, the UI does not enforce any constraints and the users are typing in whatever they want.

What I'm looking for is a Java API that can make a best-effort to convert these into a consistent format. Ideally, the API would take the free text value and a country code and produce a valid international phone number or throw an exception.

For example, a phone number in the system might look like any of the following:

(555) 478-1123 555-478-1123     555.478.1123 5554781123 

Given the country of US, the API would produce the value "+1 (555) 478-1123" for all these. The exact format does not matter, as long as it's consistent.

There are also numbers in the system without area codes, such as "478-1123". In that case, I would expect a NoAreaCodeException, or something similar.

There could also be data such as "abc", which should also throw exceptions.

Of course, there are countless variations of the examples I have posted, as well as the enormous complication of international phone numbers, which have quite complicated validation rules. This is why I would not consider rolling my own.

Has anyone seen such an API?

like image 490
Chase Seibert Avatar asked Jan 28 '09 14:01

Chase Seibert


People also ask

Is NumberFormat thread safe?

NumberFormat is not thread safe.

What is a Libphonenumber Android?

Libphonenumber is Google's formatting, parsing, and validation tool for international phone numbers. Learn how to use it in your global apps with this comprehensive guide.

What type variable is returned by the format method of the NumberFormat class?

Returns an integer number format for the specified locale.


2 Answers

You could write your own (for US phone # format):

  • Strip any non-numeric characters from the string
  • Check that the remaining string is ten characters long
  • Put parentheses around the first three characters and a dash between the sixth and seventh character.
  • Prepend "+1 " to the string


Update:

Google recently released libphonenumber for parsing, formatting, storing and validating international phone numbers.

like image 200
Bill the Lizard Avatar answered Sep 24 '22 21:09

Bill the Lizard


You could try this Java phone number formatting library https://github.com/googlei18n/libphonenumber

It has data for hundreds of countries and formats.

like image 38
g1smd Avatar answered Sep 25 '22 21:09

g1smd