Sam Leurs
Sam Leurs

Reputation: 2010

libphonenumber-js: get international format when providing number without country calling code

I want to get the international format of a phone number without providing the country calling code AND the country with libphonenumber-js.

I am from Belgium, or country calling code is +32 and our mobile phone numbers look like 0470123456. If I provide only '0470123456', I want the result to be '+32470123456', so that libphonenumber-js detects the country automatically and gives me back the international formatted phone number.

This is what I have so far:

import {parsePhoneNumber} from "libphonenumber-js";

const phone = parsePhoneNumber('0470123456');

if (phone) {
  document.getElementById("app").innerHTML = `${phone.number}`;
} else {
  document.getElementById("app").innerHTML = 'not valid';
}

This code gives me an error:

ParseError: INVALID_COUNTRY

The following code works:

import {parsePhoneNumber} from "libphonenumber-js";

const phone = parsePhoneNumber('0470123456', 'BE');

if (phone) {
  document.getElementById("app").innerHTML = `${phone.number}`;
} else {
  document.getElementById("app").innerHTML = 'not valid';
}

But as you can see, I provided the country code (BE). I don't want to do this, I want to detect the country automatically without providing the country calling code in the phone number, just detecting it by the format of the national number.

Is this possible with this library?

Upvotes: 1

Views: 408

Answers (1)

Lucas Mendonca
Lucas Mendonca

Reputation: 436

I don't think this is possible, since without providing the country calling code (+32) or the country code (BE), there are other countries where this phone number could be considered valid.

To list some examples:

  • In Japan 🇯🇵 0470 is an area code for parts of Chiba Prefecture: +81 470 12 3456
  • In Sweden 🇸🇪 0470 is an area code for the Växjö region: +46 470 123 456

Upvotes: 0

Related Questions