Suraj Sanwal
Suraj Sanwal

Reputation: 790

How to deduce Country Code from Dial code?

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!

Upvotes: 1

Views: 1794

Answers (2)

IVO GELOV
IVO GELOV

Reputation: 14269

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.

Upvotes: 1

Felix Ekl&#246;f
Felix Ekl&#246;f

Reputation: 3740

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/

Upvotes: 0

Related Questions