html code

Incorporating an Input Mask into a Lightning Web Component.

Clients often express a high demand for a specific feature: the inclusion of an input mask or field masking in a form field. This article will delve into the concept of an input mask, its potential benefits, and provide a guide on implementing a straightforward input mask.lightning-input base component.

What does an input mask entail?

An input mask is a method that formats text automatically while a user inputs data into a form field. Parentheses, spaces, and dashes, for example, are applied automatically as the user types a phone number into the field.

Incorporating an input mask into the <lightning-input> component.

We’ll be utilizing the Salesforce <lightning-input> component to implement a straightforward US phone number input mask. The <lightning-input> component provides access to existing attributes and methods, including validity checking and reporting. This accelerates development as there’s no need to recreate functionality that’s already available.

Begin by creating a custom LWC and incorporating the <lightning-input> component into the HTML file. Since we’re implementing custom validation and our event handler, set the type to “text.” Given that “text” is the default type, there’s no need to explicitly define the type attribute. Introduce a regex pattern for validation, specifying that the phone number should follow the format “(xxx) xxx-xxxx.”

The onchange() method will capture the user’s input, apply the input mask, and then return the formatted value 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>

Regex Playtime

You might have come across the following quote from the renowned software programmer at some point:

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

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