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. On the off chance that the web form is accessible internationally, the country code is compulsory for the telephone input. Since the dial code will be distinctive for the diverse country. For this situation, the client needs to enter the phone number with their country code. You can add dial code dropdown to the telephone input field to allows the client to select their country code without composing manually.

Displaying country flag and international dial code makes the telephone number input user-friendly. You can without much of a stretch include the country code select box with national flags to input field utilizing jQuery. In this instructional exercise, we will tell you the best way to actualize global telephone input field with national flags and dial codes dropdown rundown utilizing jQuery.

The International Telephone Number Input field is a straightforward jQuery plugin to add a dropdown rundown to the input field. It will list all the country names, national flags and global dial codes on the telephone input field. This plugin is exceptionally helpful when you have to provide a telephone input field for global clients.

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 presenting the client's input to the server-side content, the telephone number validation in the customer side is dependably a prescribed advance. The accompanying code scrap tells you the best way to validate the quantity 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() technique provides different setup alternatives to redo and broaden the usefulness of the International Telephone Input plugin. Some most helpful choices of the intlTelInput plugin are given beneath.

  • allowDropdown – (Boolean) (Default: genuine) Whether the dropdown is empowered or not. Whenever crippled, dropdown rundown won't show up on the input component and the flag won't be interactive.
  • autoHideDialCode – (Boolean) (Default: genuine) Remove the dial code from input field on haze or submit.
  • autoPlaceholder – (String) (Default: amiable) Set placeholder in the input field.
  • customPlaceholder – (String) (Default: ") Append country dropdown to a particular component.
  • dropdownContainer – (String) (Default: ”) Append country dropdown to a specific element.
  • excludeCountries – (Boolean) (Default: genuine) Format the input an incentive during instatement.
  • 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 consequence of getNumber.
  • initialCountry – (String) (Default: ") Specify the country code to set the underlying country selection. Set it to "auto" to get the client's area by IP address utilizing geoIpLookup alternative.
  • nationalMode – (Boolean) (Default: genuine) Allow the client to enter the number without worldwide 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.

Related Articles

Comments 0