In this blog we will give you simple JavaScript code which used to format phone number as per given country phone format . Suppose that you have input field for phone number and you want auto format that phone number as a user type to your given phone Format / Masked , then this tutorial will help you to solve your issue with simple JavaScript , without using any Library / Plugin.
Here we are using custom format but as per your need your can create a format for all countries or you can use ITI plugin which provide all basic information about countries telephone numbers , here I have blog for how to use ITI in LWC .
We will need input box where user can enter phone number , I am using lighting input , but you can use simple HTML input as well.
<template>
<div class="slds-m-left_xx-large">
<div class="slds-size_1-of-2">
<lightning-input label="Enter Phone Number" placeholder={placeHolder} value={phoneNumberEntered} onkeydown={handlePhoneChange} maxlength={formatLen}></lightning-input>
</div>
</div>
</template>
On our input box we have onkeydown={handlePhoneChange} event which takes care of validating phone number as user types.
import { LightningElement, track} from 'lwc';
export default class MaskedPhoneNumber extends LightningElement {
indiaFormat = '12345 67890';
USFormat = '(000) 123-4567'
placeHolder = this.indiaFormat
@track formatLen = this.placeHolder.length
@track phoneNumberEntered = '';
handlePhoneChange(event) {
let getIndexOfSpecialChar = [];
let getactualSpecialChar = [];
for (let i = 0; i < this.placeHolder.length; i++) {
if(this.placeHolder[i] == ' ' || this.placeHolder[i] == '(' || this.placeHolder[i] == ')'
|| this.placeHolder[i] == '-' ) {
getIndexOfSpecialChar.push(i);
getactualSpecialChar.push(this.placeHolder[i]);
}
}
[]
let len = event.target.value.length;
let backspace= event.keyCode;
if(backspace == 8 ) {
len = len-1;
}else {
len = event.target.value.length
}
let eventTargetValue = event.target.value
for(let i = 0;i < this.placeHolder.length; i++){
if(len == getIndexOfSpecialChar[i]) {
this.phoneNumberEntered = eventTargetValue + getactualSpecialChar[i];
if(this.phoneNumberEntered.length == getIndexOfSpecialChar[i+1]) {
this.phoneNumberEntered = this.phoneNumberEntered + getactualSpecialChar[i+1];
}
}
}
}
}
Our final phone number as stored in phoneNumberEntered variable , watch the following Youtube video to understand how this JavaScript Code works .