Java phone number format API
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.
Simple regex parser
/**
* @param pPhoneNumber
* @return true if the phone number is correct
*/
private boolean isPhoneNumberCorrect(String pPhoneNumber) {
Pattern pattern = Pattern
.compile("((\\+[1-9]{3,4}|0[1-9]{4}|00[1-9]{3})\\-?)?\\d{8,20}");
Matcher matcher = pattern.matcher(pPhoneNumber);
if (matcher.matches()) return true;
return false;
}
Format
I made this according to my needs, and it accepts numbers:
- CountryCode-Number
- Number
Country Codes:
They may have a: +
, or either one or two zeros.
Then, it may be followed by a -
.
Accepts:
+456
00456
+1234
01234
All above may or may not followed by a -
Rejects:
0456
- it should be:
00456
or+456
or04444
- it should be:
Number
A simple number with 8-20 digits.
Accepts:
00456-12345678
+457-12345678
+45712345678
0045712345678
99999999
Extend it?
Feel free, so you may include support for .
or '(' separators. Just make sure you escape them, e.g. for (
use \(
.
You could try this Java phone number formatting library https://github.com/googlei18n/libphonenumber
It has data for hundreds of countries and formats.