EP-32 | How to Apply Input Mask in LWC | LWC Stack ☁️⚡️

 LWC Stack is Lightning Web Component tutorial series by Salesforce MVP Kapil Batra. In this series you will find LWC tutorials from beginner to intermediate level.

So if you are working on it or planning to learn LWC then this video series is for you. Let's learn and grow together !

Please check complete code below from LWC Stack EP-32

Using input mask you can format the input text with a specific REGEX i.e. Phone Number, SSN or any other format.
The text will be converted live on the on change event of the lightning-input. Please checkout complete code below : 

HTML
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<template>
  <lightning-card
    title="Input Mask in Lightning Web Component"
    icon-name="utility:phone"
  >
    <div style="padding: 10px">
      <lightning-input
        name="PhoneNumber"
        label="Phone Number"
        value={phoneNumber}
        pattern="^\(\d{3}\)\s\d{3}-\d{4}$"
        message-when-pattern-mismatch="Phone number is not valid"
        message-when-value-missing="Phone number is required"
        onchange={handleInputMask}
        required
      >
      </lightning-input>
    </div>
  </lightning-card>
</template>

JavaScript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import { LightningElement } from "lwc";

export default class InputMask extends LightningElement {
  phoneNumber;

  handleInputMask(event) {
    const x = event.target.value
      .replace(/\D+/g, "")
      .match(/(\d{0,3})(\d{0,3})(\d{0,4})/);

    event.target.value = !x[2]
      ? x[1]
      : `(${x[1]}) ${x[2]}` + (x[3] ? `-${x[3]}` : ``);
  }
}

Output


Checkout complete video output below 

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments