Phone number with Flag in LWC

by Rijwan Mohmmed
phone-number-with-flag-in-lwc-techdicer

Hello friends, today we are going to discuss Phone number with Flag in LWC. Phone numbers often have varying formats and country codes. When users are required to input phone numbers, providing visual feedback about the country associated with the number can significantly reduce errors and streamline data entry. This is where Phone Number Flags come into play.

Also, check this: MultiSelect Picklist In LWC Datatable Inline Edit

Key Highlights :

  1. Reduced Errors: Phone Number Flags help users quickly identify the expected format of the phone number, reducing mistakes and typos during data entry.
  2. Efficiency: Users can immediately recognize the appropriate country flag, saving them time and effort in searching for the correct country code.
  3. Global Appeal: In multinational businesses, Phone Number Flags accommodate users from various regions, creating an inclusive and user-friendly environment.
  4. We use the third-party library to implement this.

Code :

Step 1: First of all upload the intl-tel-input zip library in static resource so this can load in the LWC .

Step 2: Now we create the LWC component

lWCFlagTelephone.HTML :

<template>
	<lightning-card title="LWC Telephone with Flag Picker" icon-name="standard:event">
		<div class="slds-p-around_large">
			<div class="slds-form-element__control">
				<input type="tel" class="slds-input" data-id="phone" name="phone" onkeyup={handleFieldChange}></input>
			</div>
		</div>
	</lightning-card>
</template>

lWCFlagTelephone.JS :

import { LightningElement } from 'lwc';
import flagTelpicker from '@salesforce/resourceUrl/flagTelpicker';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';


export default class LWCFlagTelephone extends LightningElement {
    datepickerInitialized = false;
    //https://www.jqueryscript.net/form/jQuery-International-Telephone-Input-With-Flags-Dial-Codes.html

    renderedCallback(){
        if(this.datepickerInitialized){
            return;
        }
        this.datepickerInitialized = true;
 
        Promise.all([
            loadStyle(this,flagTelpicker + '/css/demo.css'),
            loadStyle(this,flagTelpicker + '/css/intlTelInput.css'),
            loadScript(this, flagTelpicker + '/js/utils.js'),
            loadScript(this, flagTelpicker + '/js/intlTelInput.js')
        ]).then(() => {
            this.initFlagpicker();
        })
        .catch(error => {
            console.log(error);
        });
    }

    initFlagpicker(){
        const input = this.template.querySelector("[data-id=phone]");

        window.intlTelInput(input, {
            separateDialCode: true,
            excludeCountries: ["il"],
            preferredCountries: ["ru", "jp", "pk", "no"],
            initialCountry: "IN",
        });

        /*
        // whether or not to allow the dropdown
        allowDropdown: true,

        // when enabled (requires nationalMode to be disabled), the international dial code will be automatically inserted into the input in 3 situations: (A) upon initialisation, and (B) when the user selects a country from the dropdown, and (C) upon calling setCountry. Additionally, the plugin will listen for blur/submit events, and if the input only contains a dial code, it will automatically be removed to avoid submitting just that.
        autoInsertDialCode: true,

        // add a placeholder in the input with an example number for the selected country
        autoPlaceholder: "polite",

        // modify the auto placeholder
        customPlaceholder: null,

        // append menu to specified element
        dropdownContainer: null,

        // don't display these countries
        excludeCountries: [],

        // format the input value during initialisation and on setNumber
        formatOnDisplay: true,

        // geoIp lookup function
        geoIpLookup: null,

        // inject a hidden input with this name, and on submit, populate it with the result of getNumber
        hiddenInput: "",

        // initial country
        initialCountry: "",

        // localized country names e.g. { 'de': 'Deutschland' }
        localizedCountries: null,

        // don't insert international dial codes
        nationalMode: true,

        // display only these countries
        onlyCountries: [],

        // number type to use for placeholders
        placeholderNumberType: "MOBILE",

        // the countries at the top of the list. defaults to united states and united kingdom
        preferredCountries: [ "us", "gb" ],

        // display the country dial code next to the selected flag so it's not part of the typed number
        separateDialCode: false,

        // show/hide the flags
        showFlags: true,

        // specify the path to the libphonenumber script to enable validation/formatting
        utilsScript: ""
        */
    }

    handleFieldChange(event){
        console.log(event.target.value);
    }
}

lWCFlagTelephone.JS-meta.xml :

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>57.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
	</targets>
</LightningComponentBundle>

Output :

phone-number-with-flag-in-lwc-techdicer

Reference :

  1. Tel JS
What’s your Reaction?
+1
2
+1
0
+1
0
+1
0
+1
0
+1
0

You may also like

Leave a Comment