4

I am using libPhone library in angular js application to validate if the phone numbers are valid. However I have to show the valid format that the user has to provide in case the phone number entered is invalid.

The user will provide the country code and the phone number. For example if the user needs to provide a U.S number, then the format to be shown to the user is : xxx-xxx-xxxx

I was trying to do that by using a work around, illustrating that for a Mexican number by calling getPhoneFormat('mx')

  var getPhoneFormat = function(countryCode) {
         var exampleNum = phoneUtil.getExampleNumberForType(countryCode, libphonenumber.PhoneNumberType.MOBILE);
         var formattedNum =  phoneUtil.format(exampleNum, libphonenumber.PhoneNumberFormat.RFC3966);
         //formattedNum -> tel:+52-1-222-123-4567

         //then i was thinking of removing the prefix by checking the position of the 1st '-'
          var removeFromIndex =  formattedNum.indexOf('-') + 1
          var validFormat =  formattedNum.substring(removeFromIndex);
          //valid format is ->   1-222-123-4567

          //finally replace numbers with x and return
     }

Is there some methods that the library provides to satisfy the same requirements? I saw formatByPattern but not sure how to use it.

dream123
  • 129
  • 3
  • 14

1 Answers1

1

Have you tried this smaller version? It has a parse and a formate.

i.e.

parse('8 (800) 555 35 35', 'RU')
// { country: 'RU', phone: '8005553535' }

format('2133734253', 'US', 'International')
// '+1 213 373 4253'

In your case you'd prob want to use

"National" instead of International

https://github.com/catamphetamine/libphonenumber-js

user1819575
  • 176
  • 1
  • 7