Sam Leurs
Sam Leurs

Reputation: 2000

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: 373

Answers (0)

Related Questions