International Telephone Input with Country Flags and Dial Codes using jQuery

Telephone number input field is a commonly used field in the web form where the user can provide their contact info. If the web form is available internationally, the country code is mandatory for the telephone input. Because the dial code will be different for the different country. In this case, the user needs to enter the phone number with their country code. You can add dial code dropdown to the telephone input field to allows the user to select their country code without typing manually.

Displaying country flag and international dial code makes the telephone number input user-friendly. You can easily add the country code select box with national flags to input field using jQuery. In this tutorial, we will show you how to implement international telephone input field with national flags and dial codes dropdown list using jQuery.

The International Telephone Number Input field is a simple jQuery plugin to add a dropdown list to the input field. It will list all the country names, national flags and international dial codes on the telephone input field. This plugin is very useful when you need to provide a telephone input field for international users.

CSS

Include the stylesheet file of the intlTelInput plugin, it will style the international telephone input dropdown list.

<link rel="stylesheet" href="css/intlTelInput.css">

HTML

Add an input field to accept the telephone input from the user. The country code dropdown list will be added to this HTML element.

<input type="tel" id="phone">

JavaScript

Include the JS library of International Telephone Input plugin.

<script src="js/intlTelInput.js"></script>

Use the intlTelInput() method to initialize the International Telephone Input plugin. It will replace an HTML input element with dial code dropdown list and country flags.

<script>
var input = document.querySelector("#phone");
window.intlTelInput(input);
</script>

Basic Uses

The following example code snippet adds international telephone dial codes select box to the input field. Use utilsScript option and specify the utils.js script URL to enable the international formatting or validation.

var input = document.querySelector("#phone");
intlTelInput(input, {
    utilsScript: "js/utils.js"
});

Set Initial Country Based on IP address

Use initialCountry with the geoIpLookup option to set a default country dial code based on the user’s IP address.

For this advance feature of International Telephone Input plugin, you need to include jQuery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Set the initialCountry option to auto and specify a custom function in the geoIpLookup option. Use the ipinfo.io service that will lookup the user’s country based on their IP address and set the initial dial code in the telephone input.

var input = document.querySelector("#phone");
intlTelInput(input, {
    initialCountry: "auto",
    geoIpLookup: function(success, failure) {
        $.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
            var countryCode = (resp && resp.country) ? resp.country : "";
            success(countryCode);
        });
    },
    utilsScript: "js/utils.js"
});

Telephone Number Validation

Before submitting the user’s input to the server-side script, the telephone number validation in the client-side is always a recommended step. The following code snippet shows you how to validate the number of International Telephone Input field with the intlTelInput plugin.

Define the HTML elements with Telephone Input field where the error/success message will be shown.

<input type="tel" id="phone">
<span id="valid-msg" class="hide">✓ Valid</span>
<span id="error-msg" class="hide"></span>

Use the isValidNumber method to check whether the user enters a valid telephone number based on the country dial code. On the blur event, the telephone number validation function will trigger.

var input = document.querySelector("#phone"),
    errorMsg = document.querySelector("#error-msg"),
    validMsg = document.querySelector("#valid-msg");

// Error messages based on the code returned from getValidationError
var errorMap = [ "Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];

// Initialise plugin
var intl = window.intlTelInput(input, {
    utilsScript: "js/utils.js"
});

var reset = function() {
    input.classList.remove("error");
    errorMsg.innerHTML = "";
    errorMsg.classList.add("hide");
    validMsg.classList.add("hide");
};

// Validate on blur event
input.addEventListener('blur', function() {
    reset();
    if(input.value.trim()){
        if(intl.isValidNumber()){
            validMsg.classList.remove("hide");
        }else{
            input.classList.add("error");
            var errorCode = intl.getValidationError();
            errorMsg.innerHTML = errorMap[errorCode];
            errorMsg.classList.remove("hide");
        }
    }
});

// Reset on keyup/change event
input.addEventListener('change', reset);
input.addEventListener('keyup', reset);

Configuration Options

The intlTelInput() method provides various configuration options to customize and extend the functionality of the International Telephone Input plugin. Some most useful options of the intlTelInput plugin are given below.

  • allowDropdown – (Boolean) (Default: true) Whether the dropdown is enabled or not. If disabled, dropdown list will not appear on the input element and the flag will not be clickable.
  • autoHideDialCode – (Boolean) (Default: true) Remove the dial code from input field on blur or submit.
  • autoPlaceholder – (String) (Default: polite) Set placeholder in the input field.
  • customPlaceholder – (Function) (Default: null) Change the auto placeholder with custom string.
  • dropdownContainer – (String) (Default: ”) Append country dropdown to a specific element.
  • excludeCountries – (Array) (Default: undefined) Display all countries except the specified ones.
  • formatOnDisplay – (Boolean) (Default: true) Format the input value during initialization.
  • geoIpLookup – (Function) (Default: null) Specify a custom function that looks up the user’s location.
  • hiddenInput – (String) (Default: ”) Add a hidden input with the given name, and on submit, populate it with the result of getNumber.
  • initialCountry – (String) (Default: ”) Specify the country code to set the initial country selection. Set it to “auto” to get the user’s location by IP address using geoIpLookup option.
  • nationalMode – (Boolean) (Default: true) Allow the user to enter the number without international dial codes.
  • placeholderNumberType – (String) (Default: MOBILE) Specify the number type to use for placeholders.
  • onlyCountries – (Array) (Default: undefined) Display only these specified countries.
  • preferredCountries – (Array) (Default: [ “us”, “gb” ]) Specify the countries to appear at the top of the list.
  • separateDialCode – (Boolean) (Default: false) Display the country dial code next to the selected flag.
  • utilsScript – (String) (Default: ”) Specify the path to the libphonenumber script to enable validation/formatting.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

5 Comments

  1. Brett H Said...
  2. Hayden Ng Said...
  3. Ajit Kar Said...
  4. Giri Said...
  5. KIm Said...

Leave a reply

keyboard_double_arrow_up