Skip to content

Instantly share code, notes, and snippets.

@mwender
Created October 25, 2024 21:08
Show Gist options
  • Save mwender/345690a54be1e5e202ee92eb8c3a71ad to your computer and use it in GitHub Desktop.
Save mwender/345690a54be1e5e202ee92eb8c3a71ad to your computer and use it in GitHub Desktop.
[applyPhoneMask.js] Phone number masking for text fields. #javascript
/**
* Apply phone number masking to a specified input field.
*
* This function attaches an input event listener to the form field identified by the given ID.
* It ensures that the phone number entered is formatted in the (XXX) XXX-XXXX pattern as the user types.
*
* The function removes non-digit characters from the input and limits the input length to 10 digits.
* It adjusts the formatting dynamically based on the number of digits entered:
* - Up to 3 digits: (XXX
* - 4 to 6 digits: (XXX) XXX
* - 7 to 10 digits: (XXX) XXX-XXXX
*
* @param string $fieldId The ID of the input field to apply the phone number mask to.
*/
function applyPhoneMask(fieldId) {
const inputField = document.getElementById(fieldId);
if (inputField) {
inputField.addEventListener('input', (e) => {
let input = e.target.value.replace(/\D/g, ''); // Remove all non-digit characters
if (input.length > 10) input = input.substring(0, 10); // Limit input to 10 digits
// Format input as (XXX) XXX-XXXX
if (input.length > 6) {
input = `(${input.substring(0, 3)}) ${input.substring(3, 6)}-${input.substring(6, 10)}`;
} else if (input.length > 3) {
input = `(${input.substring(0, 3)}) ${input.substring(3)}`;
} else {
input = `(${input}`;
}
e.target.value = input;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment