Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using PhoneNumberFormat from 'google-libphonenumber' does not work

I wanted to format a phone number using the google-libphonenumber library. I do not want to use Require, instead want to use ES6 imports. But it does not seem to work

import { PhoneNumberUtil, PhoneNumberFormat } from 'google-libphonenumber'

const phoneUtil = PhoneNumberUtil.getInstance()
let number = phoneUtil.parse(target.value, 'US') . //works
let valid = phoneUtil.isValidNumber(number) .   //works
console.log(phoneUtil.format(phone, PhoneNumberFormat.INTERNATIONAL)) //does not work

I later tried using require

const PNF = require('google-libphonenumber').PhoneNumberFormat

console.log(phoneUtil.format(phone, PNF.INTERNATIONAL))

That also gives error

TypeError: a.getNationalNumber is not a function
i18n.phonenumbers.PhoneNumberUtil.format
node_modules/google-libphonenumber/dist/browser/libphonenumber.js:5435
like image 434
Kimaya Avatar asked Jan 31 '26 03:01

Kimaya


1 Answers

It seems in your case you passed phone instead of number

This function expects a "PhoneNumber" object

import {
  PhoneNumberUtil,
  // using PNF alias to follow along with documentaion
  PhoneNumberFormat as PNF
} from 'google-libphonenumber';

  // grab your instance
  const phoneUtil = PhoneNumberUtil.getInstance();

  // here we are parse our number into that object
  const number = phoneUtil.parse('121231234', 'ZA');

  console.log(phoneUtil.isPossibleNumber(number));
  console.log(phoneUtil.format(number, PNF.INTERNATIONAL));
like image 165
loekTheDreamer Avatar answered Feb 01 '26 19:02

loekTheDreamer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!