Adding an Input Mask to a Lightning Web Component

599 Views
LWC Input Mask

One of the most requested features clients ask for is the addition of an input mask or field masking to a form field. This post will explain what an input mask is, why you may want to use one, and how we can apply a simple input mask to the lightning-input base component.

What is an input mask?

An input mask is a technique that automatically formats text as a user types in an input form field. The parentheses, spaces and dashes are automatically applied as the phone number is typed into the field:

phone field  input mask

Adding an input mask to the <lightning-input> component

We’re going to be using the Salesforce <lightning-input> component and adding a simple US phone number input mask. The <lightning-input> component allows us to leverage existing attributes and methods including validity checking and reporting. This will greatly speed up development as we won’t have to recreate what’s already been built.

Create a custom LWC and add the <lightning-input> component to the HTML file. We have to use custom validation and our own event handler so we need to set the type to “text”. Since “test” is the default type, we don’t have to define the type attribute. Add the regex pattern to validate against – the input expects the phone number to be formatted as “(xxx) xxx-xxxx”.

The onchange() method is going to grab the input as the user types, apply the input mask and return the formatted value back to the <lighting-input>:

<lightning-input name="Phone"
                 label="Phone"
                 value={phone}
                 pattern="^\(\d{3}\)\s\d{3}-\d{4}$"
                 message-when-pattern-mismatch="Not a valid phone number"
                 message-when-value-missing="Phone number is required"
                 onchange={handlePhoneInputMask}
                 required>
</lightning-input>

Fun with Regex

At some point you may have run across this quote from famed software programmer, Jami Zawinski:

Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.

Jamie Zawinski

Add the handlePhoneInputMask() function to the LWC JavaScript file. Set a variable to the input value. The regex on Line #10 replaces any character that’s not a digit (you could also use [^0-9]) as it is being typed into the field. Then, we conditionally mask the number based on the regex match() method and return the value back to the <lightning-input> using the new format.

Here is an explaination of the regex match courtesy of regex101.com:

  • 1st Capturing Group (\d{0,3})
    • \d{0,3}matches a digit (equal to [0-9])
      {0,3} Quantifier — Matches between 0 and 3 times, as many times as possible, giving back as needed
  • 2nd Capturing Group (\d{0,3})
    • \d{0,3} matches a digit (equal to [0-9])
      {0,3} Quantifier — Matches between 0 and 3 times, as many times as possible, giving back as needed
  • 3rd Capturing Group (\d{0,4})
    • \d{0,4} matches a digit (equal to [0-9])
      {0,4} Quantifier — Matches between 0 and 4 times, as many times as possible, giving back as needed
import {LightningElement} from 'lwc';

export default class InputMask extends LightningElement {

    phone;

    handlePhoneInputMask(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]}` : ``);
    }
}

Credit/Source : http://lightningpowered.dev/adding-an-input-mask-to-a-lightning-web-component/

Leave a Comment