Mobile number masking in Salesforce Aura or Lightning 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:

Why would I want to use an input mask?

Data Integrity

Let’s say your system of record requires all phone numbers to be entered in US format with a hyphen and the zip code in parentheses. An input mask simplifies data entry by only allowing the user to type numbers (0-9) while the parentheses and hyphen are automatically added in the correct location.

Enhanced User Experience

When a user enters information into a form field, they will often wonder whether they should type symbols or not. Users who choose to type the format will need to press extra keys to include the symbols. More typing increases the chance of errors. This can also slow down data entry.

Fields that may accept multiple formats – like the phone number example above – may cause uncertainty for the user. For example, users could use hyphens or periods to separate strings on a phone number. They may include parentheses around the zip code or not. The input mask removes these uncertainties.

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>:

inputMask.html

<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>
<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>
<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

Following this advice has served me well throughout my career, but for this component, we’re going to have to bite the bullet and use regular expressions. Thankfully, we have some fantastic online tools at our disposal for testing, debugging and learning these regular expressions. The one I use is regex101.com.

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

inputMask.js

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

Code Reusability and Example App

In a real-world application, you may want to move your input mask functions to an ES6 module:

inputMaskUtils.js

const phoneMask = (val) => {
const x = val.replace(/\D+/g, ).match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
return !x[2] ? x[1] : `(${x[1]}) ${x[2]}` + (x[3] ? `-${x[3]}` : );
};
export { phoneMask }
const phoneMask = (val) => { const x = val.replace(/\D+/g, ”).match(/(\d{0,3})(\d{0,3})(\d{0,4})/); return !x[2] ? x[1] : `(${x[1]}) ${x[2]}` + (x[3] ? `-${x[3]}` : “); }; export { phoneMask }
const phoneMask = (val) => {
    const x = val.replace(/\D+/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
    return !x[2] ? x[1] : `(${x[1]}) ${x[2]}` + (x[3] ? `-${x[3]}` : ``);
};

export { phoneMask }

Then import the functions as needed in your LWC:

inputMask.js

import {LightningElement} from ‘lwc’;
import { phoneMask } from ‘c/inputMaskUtils’;
export default class InputMask extends LightningElement {
phone;
handlePhoneInputMask(event) {
event.target.value = phoneMask(event.target.value);
}
}
import {LightningElement} from ‘lwc’; import { phoneMask } from ‘c/inputMaskUtils’; export default class InputMask extends LightningElement { phone; handlePhoneInputMask(event) { event.target.value = phoneMask(event.target.value); } }
import {LightningElement} from 'lwc';
import { phoneMask } from 'c/inputMaskUtils';

export default class InputMask extends LightningElement {

    phone;

    handlePhoneInputMask(event) {
        event.target.value = phoneMask(event.target.value);
    }
}

To see how you might use this in an app, I created a simple lightning form that updates a contact record. View the code example on Github.

Are you working on Mobile number manipulation or validation in our Salesforce forms ??? Here we gonna do mobile number masking for US format. once user input is done. our Aura component JavaScript controller automatically formats your mobile number.

  • Create a Lightning component in your salesforce org
  • Add a lighting input field in your component.
  • Work with Aura attributes and Id to capture the formatted values.
  • Add onblur event in your lightning input field and write functionality on your controller. Here you can check the code for your reference.
<aura:component>

  <aura:attribute name="mobile" type="String" default=""/>


 <lightning:input class="slds-col slds-size_1-of-2 slds-p-top_small" 
                  name="Phone"
                  aura:id="mobile" 
                  type="text" 
                  placeholder="mobile" 
                  label="mobile" 
                  variant="label-hidden" 
                  value="{!v.mobile}" 
                  onblur="{!c.mobileNumberFormater}" maxlength="10" minlength = "10"/>

</aura:component>
     mobileNumberFormater: function(component, event, helper){

         var phoneNumber = component.get('v.mobile');
         var cleaned = ('' + phoneNumber).replace(/\D/g, '');
          var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
          if (match) {
            var finalOne="(" + match[1] + ') ' + match[2] + '-' + match[3];
             component.set("v.mobile", finalOne);

          }
          return null;
              
    }

Leave a Comment

Your email address will not be published.

Scroll to Top