Created
April 4, 2023 12:35
-
-
Save gixxerblade/fdfcc85318a6ca6bf70481b3115dc650 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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