LWC – Formatted Mobile Number Validation
Ensuring Clean Phone Numbers in Your Lightning Web Components
A user-friendly interface is crucial for any application, and that includes capturing data in a clean and consistent format. Phone numbers are a prime example. While users may enter their phone numbers with variations (hyphens, spaces, parentheses), having them stored in a standard format is essential for downstream processes.
This blog post will explore how to achieve this using a combination of the lightning-input
component and a custom JavaScript function in a Lightning Web Component (LWC).
The Lightning Input Component
The lightning-input
component provides a versatile way to capture user input in your LWC. By setting the type
attribute to "tel"
, the browser will offer helpful input hints for phone numbers on mobile devices.
Here’s the relevant code snippet for our example:
We’ve included several key attributes here:
label
: This sets the label displayed for the input field.name
: This assigns a name to the input field for form submission purposes.onchange
: This binds a JavaScript function (validatePhoneOnChange
) to execute whenever the value in the input field changes.value
: This two-way data binds theformattedPhoneNumber
property to the input field’s value.pattern
: This attribute defines a regular expression pattern to validate the user’s input. In this case, it ensures the format(XXX)-XXX-XXXX
.message-when-pattern-mismatch
: This sets the error message displayed when the user enters an invalid phone number format.
The validatePhoneOnChange Function
The validatePhoneOnChange
function plays a critical role in cleaning and formatting the phone number as the user types. Here’s a breakdown of its functionality:
validatePhoneOnChange(event){
const inputPhoneNumber = event.target.value;
const cleanedPhoneNumber = (""+inputPhoneNumber).replace(/\D/g, '');
const phNumberMatch = cleanedPhoneNumber.match(/^(\d{3})(\d{3})(\d{4})$/);
const formattedPhone = (!phNumberMatch) ? null : `(${phNumberMatch[1]})-${phNumberMatch[2]}-${phNumberMatch[3]}`;
this.formattedPhoneNumber= (formattedPhone == null) ? inputPhoneNumber : formattedPhone;
}
Format (000)-000-0000, if you do not wan’t the brackets simply remove it from formattedPhone concatenation and update the regex pattern on html file as per your need. Below is the result:

- Extracting the Input: The function first retrieves the current value from the input field using
event.target.value
. - Removing Non-Digits: It then removes any non-numeric characters using a regular expression (
/\D/g, '')
). This ensures we only work with the actual digits of the phone number. - Validating and Formatting: The function attempts to match the cleaned phone number against a regular expression pattern
^(\d{3})(\d{3})(\d{4})$
. This pattern ensures three digits followed by an optional group separator (like a hyphen), another three digits, another separator, and finally four digits.- If there’s a match (
phNumberMatch
is not null), the function creates a formatted phone number string by inserting parentheses, hyphens, and capturing the matched groups. - If there’s no match (
phNumberMatch
is null), it indicates an invalid format, and the function leaves the value unchanged.
- If there’s a match (
- Updating the State: Finally, the function updates the
formattedPhoneNumber
property of the component with either the formatted value or the original input depending on the validation outcome. This two-way data binding ensures the input field reflects the formatted value.
Conclusion
By combining the lightning-input
component with a custom validation function, you can ensure consistent and clean phone number data in your LWC applications. This improves data quality and streamlines downstream processes that rely on phone numbers.
Additional Considerations:
- You can customize the regular expression pattern to accommodate different phone number formats based on your region or use case.
- Consider internationalization (i18n) for handling phone number formats from various countries.