How to format a phone numbers with libphonenumber in International format.
Asked Answered
B

2

18

In the documentation provided by libphonenumber on Github, there is a demo, which converts any provided number into International Format, e.g +4915213116250 is converted into +49 1521 3116250

I want to use the same functionality in C#.

In the documentation of libphone, there is need to parse the number and provide the countries/regions. But the demo works without providing the region/country. Can some body let me know how it is done?

Berberidaceous answered 24/7, 2015 at 13:11 Comment(0)
C
27

Have you tried this?

var phoneUtil = PhoneNumberUtil.GetInstance();
var numberProto = phoneUtil.Parse("1234567890", "IT");
var formattedPhone = phoneUtil.Format(numberProto, PhoneNumberFormat.INTERNATIONAL);

This will give you "+39 123 456 7890"

Coelenterate answered 23/3, 2016 at 10:22 Comment(2)
How to validate phone number? I don't know how to set PhoneNumber - it has a lot of params, but mostly they are readonly.Ocular
@Ocular use phoneUtil.Parse and then phoneUtil.IsValidNumberFreddyfredek
F
2

@danyolgiax almost had it. Here's what you do:

var phoneUtil = PhoneNumberUtil.GetInstance();
var numberProto = phoneUtil.Parse("+4915213116250", "ZZ"); //why ZZ means international i don't know
var formattedPhone = phoneUtil.Format(numberProto, PhoneNumberFormat.INTERNATIONAL);

Remember to use phoneUtil.IsValidNumber if you aren't certain that the phone number is valid. Also be aware that phoneUtil.Parse may throw.

Freddyfredek answered 11/1, 2021 at 13:23 Comment(1)
ZZ dont work i get PhoneNumbers.NumberParseException: 'Missing or invalid default region.'Illustrative

© 2022 - 2024 — McMap. All rights reserved.