Reputation: 822
I need to format the number to x xxx xxx xx-xx. Here is two examples.
PhoneNumberUtils.formatNumber("+79998887766", "RU"))
Result is: "+7 999 888-77-66". This is what I need.
PhoneNumberUtils.formatNumber("+71112223344", "RU"))
Result is: "+71112223344". The number with same length is not formatted.
How to format the second number?
Upvotes: 0
Views: 2811
Reputation: 560
The second number you are passing is not valid.
Google provides a library for formatting and validating the phone numbers.
Add below dependency into your app-level build.gradle inside dependencies{}
:
compile 'com.googlecode.libphonenumber:libphonenumber:7.2.2'
Example :
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
boolean isValid;
String no;
try {
Phonenumber.PhoneNumber numberProto = phoneUtil.parse("+79112223344", "RU"); // Pass number & Country code
//check whether the number is valid or not.
isValid = phoneUtil.isValidNumber(numberProto);
if (isValid) {
no = phoneUtil.format(numberProto, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
System.out.println("Formatted Number :" + no);
} else
System.out.println("Invalid Number");
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
Upvotes: 3