Last active
January 18, 2024 11:44
-
-
Save tiagobnobrega/b7165b6adb3d9863e3f3088ebee703ab to your computer and use it in GitHub Desktop.
javascript common formatters
This file contains hidden or 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
const normalizePhone = (value: string): string => { | |
if (!value) return ''; | |
let newNumber = value.replace(/\D/g, ''); | |
newNumber = newNumber.substring(0, 11); | |
newNumber = newNumber.replace(/^(\d{2})(\d)/g, '$1 $2'); | |
newNumber = newNumber.replace(/(\d)(\d{4})$/, '$1-$2'); | |
return newNumber; | |
}; | |
const normalizeDocument = (value: string): string => { | |
if (!value) return ''; | |
let newVal = value.replace(/\D/g, ''); | |
if (newVal.length <= 11) { | |
newVal = normalizeCPF(newVal); | |
} else { | |
newVal = normalizeCNPJ(newVal); | |
} | |
return newVal; | |
}; | |
const normalizeCPF = (value: string): string => { | |
if (!value) return ''; | |
let newVal = value.replace(/\D/g, ''); | |
newVal = newVal.substring(0, 11); | |
newVal = newVal.replace(/^(\d{3})(\d)(.*)/, '$1.$2$3'); | |
newVal = newVal.replace(/^(\d{3}\.\d{3})(\d)(.*)/, '$1.$2$3'); | |
newVal = newVal.replace(/^(\d{3}\.\d{3}\.\d{3})(\d)(.*)/, '$1-$2$3'); | |
return newVal; | |
}; | |
const normalizeCNPJ = (value: string): string => { | |
if (!value) return ''; | |
let newVal = value.replace(/\D/g, ''); | |
newVal = newVal.substring(0, 14); | |
newVal = newVal.replace(/(\d{2})(\d)(.*)/, '$1.$2$3'); | |
newVal = newVal.replace(/(\d{2}\.\d{3})(\d)(.*)/, '$1.$2$3'); | |
newVal = newVal.replace(/(\d{2}\.\d{3}\.\d{3})(\d)(.*)/, '$1/$2$3'); | |
newVal = newVal.replace(/(\d{2}\.\d{3}\.\d{3}\/\d{4})(\d)(.*)/, '$1-$2$3'); | |
return newVal; | |
}; | |
/** | |
* This preserves the caret position on inputs after transformation. | |
* Call it on the onChange handler before returning the value: | |
* onChange(e)=>{ | |
* keepCaretPositionOnChange(e) | |
* const newValue = transformValueSomehow(e.target.value); | |
* //return or update the input value | |
* } | |
**/ | |
export const keepCaretPositionOnChange = ( | |
evt: ChangeEvent<HTMLInputElement>, | |
) => { | |
const caret = evt.target.selectionStart; | |
const element = evt.target; | |
window.requestAnimationFrame(() => { | |
element.selectionStart = caret; | |
element.selectionEnd = caret; | |
}); | |
}; | |
export default { | |
normalizePhone, | |
normalizeDocument, | |
normalizeCPF, | |
normalizeCNPJ, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment