1

I have a custom form made with Vue there is a field for a mobile number where I am using Vue Int Tel input package for country code dropdown with flags.

I got a country Dial code value for the selected input from the country code dropdown. I want to get the country code from the dialing code value. For example, If India is the selected country and I had a dial code value +91 How should I deduce Country code i.e. IN from that particular dial code value?

**I'm able to get both values separately, but what I can't able to do is deducing country code from dial code.

Any Help will much be appreciated!

Suraj Sanwal
  • 728
  • 1
  • 6
  • 14

2 Answers2

1

Since vue-tel-input internally uses libphonenumber-js - you can use it, too:

<template>
  <vue-tel-input ref="tel" v-model="phone" />
</template>
import parsePhoneNumberFromString from 'libphonenumber-js';

export default
{
  data()
  {
    return {
      phone: '',
    };
  },
  methods:
  {
    getCountryCode()
    {
      // vue-tel-input does not update the model if you have a default country,
      // so we have to access its internal representation
      // To avoid accessing internal data of vue-tel-input, you can either not use
      // a default country, or provide the default country as a 2nd argument to the
      // parsing function - parsePhoneNumberFromString(this.phone, this.defaultCountry)

      const result = parsePhoneNumberFromString((this.$refs.tel || {})._data.phone);
      return result.country;
    }
  }

Don't forget to add the package to your project npm install libphonenumber-js.

Suraj Sanwal
  • 728
  • 1
  • 6
  • 14
IVO GELOV
  • 13,496
  • 1
  • 17
  • 26
  • Thanks, IVO GELOV! It seems parsePhoneNumberFromString will take a formatted mobile number. I had disabled auto-formatting. Is it possible to pass only the dial code of the country and it will be converted to country code?? Or if it is possible to fetch formatted number from vue-tel-input component then i will only pass that as an argument to parsing function because I saw in my console there is formatted value inside phoneObject of vue-tel-input component – Suraj Sanwal Jan 27 '21 at 12:39
  • Search for `metadata.min.json` or something similar inside `node_modules/libphonenumber-js` – IVO GELOV Jan 27 '21 at 14:41
0

You could just create a object with each country code and number prefix like this:

country_codes = {
    '+91': 'IN',
    '+46': 'SE',
    ...
}

And the use this to "translate" number prefix to two digit country code.

country_codes['+46'] //returns 'SE'

Here you can find all country codes: https://countrycode.org/

Felix Eklöf
  • 3,253
  • 2
  • 10
  • 27