0

I have a lightning-input to display phone number in a pattern 111-111-1111.

I took a lightning-input of type text and written an onblur method handlePhone and sent the inputted phone number as parameter to it. Then I'm formatting it to show the value in above mentioned pattern. But with this, it is allowing me to enter alphabets in the input and I strictly want to restrict to numericals.

Html:

<lightning-input value={phone} type="text"  maxlength="10" onblur={handlePhone} onchange={handleInputChange} name="mobile"></lightning-input>

Js:

handlePhone(phoneNumber) {
        var s = ("" + phoneNumber).replace(/\D/g, '');
        var m = s.match(/^(\d{3})(\d{3})(\d{4})$/);
        var formatPhone = (!m) ? null : m[1] + "-" + m[2] + "-" + m[3];
        this.phone = formatPhone;
    }

When I take a lightning-input type as number , my above method is not working and showing the value as 9,99,999,9999 and not following the pattern as per my requirement. Any way to achieve this by restricting the input to numbers and also display as per the pattern?

1 Answer 1

1

You can use the lightning-input tag with type as 'tel' in lwc. There is a provision to add the required pattern as well in the pattern attribute related to the tag. You can add any regex to get the desired result

Sample:

<lightning-input type="tel" label="Phone field with pattern matching" name="phone3" value="343-343-3434" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"></lightning-input>

Sample is taken from the salesforce documentation. Refer to the link below:

https://developer.salesforce.com/docs/component-library/bundle/lightning-input/example

1
  • @sfdcDev If the answer was helpful for you in resolving the issue, mark the answer as accepted so, it will be beneficial for other members who will face similar issues in the future. Thanks! Commented Aug 1, 2024 at 9:14

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.