I need to create a phone number input with special input masking. The input will have a placeholder like this: (___) ___-____
. As the user types, the “placeholder” text should slowly be replaced by the user’s typing.
(12_) ___-____
(123) 4__-____
(123) 456-7___
My current code is broken in two ways (maybe more). It doesn’t handle backspaces correctly and it doesn’t move the user’s cursor correctly.
My format function looks like this:
export const formatTelphoneNumber = (value: string): string => {
const phoneNumber = getDigitsOnly(value)
const areaCode = phoneNumber.substring(0, 3)
const nextThree = phoneNumber.substring(3, 6)
const lastFour = phoneNumber.substring(6, 10)
const formattedAreaCode = `${areaCode}${"_".repeat(3 - areaCode.length)}`
const formattedNextThree = `${nextThree}${"_".repeat(3 - nextThree.length)}`
const formattedLastFour = `${lastFour}${"_".repeat(4 - lastFour.length)}`
return `(${formattedAreaCode}) ${formattedNextThree}-${formattedLastFour}`
}
I have a code sandbox here: https://codesandbox.io/p/sandbox/phone-number-masking-trqg64?file=%2Fsrc%2FPhoneNumberInput.tsx%3A6%2C1-18%2C2
Michael Pugh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.