Skip to content

Instantly share code, notes, and snippets.

@gixxerblade
Created April 4, 2023 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gixxerblade/fdfcc85318a6ca6bf70481b3115dc650 to your computer and use it in GitHub Desktop.
Save gixxerblade/fdfcc85318a6ca6bf70481b3115dc650 to your computer and use it in GitHub Desktop.
// Function for input mask on phone number field
// Formats XXXXXXXXXX as XXX-XXX-XXXX as you type
const normalizePhone = (value, previousValue) => {
if (!value) return value
const onlyNums = value.replace(/[^\d]/g, '') // only allows 0-9
if (!previousValue || value.length > previousValue.length) {
if (onlyNums.length === 3) return `${onlyNums}`
if (onlyNums.length === 6) return `${onlyNums.slice(0, 3)}-${onlyNums.slice(3)}-`
if (onlyNums.length <= 3) return onlyNums
if (onlyNums.length <= 6) return `${onlyNums.slice(0, 3)}-${onlyNums.slice(3)}`
return `${onlyNums.slice(0, 3)}-${onlyNums.slice(3, 6)}-${onlyNums.slice(6, 10)}`
}
}
// usage
// setPhone((prev) => normailzePhone(value, prev))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment