Mobile number masking in Salesforce Aura or Lightning component

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.

Let’s see the magic

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

Your email address will not be published.