Skip to content

Instantly share code, notes, and snippets.

@estevan-ulian
Last active October 17, 2023 00:02
Show Gist options
  • Save estevan-ulian/33c1e2db2eb9d80dca48b359d1b374a1 to your computer and use it in GitHub Desktop.
Save estevan-ulian/33c1e2db2eb9d80dca48b359d1b374a1 to your computer and use it in GitHub Desktop.
Máscara de CPF ou CNPJ para o mesmo campo de input
const inputCpfCnpj = document.querySelector('.cpf_cnpj input');
function handleInputCpfCnpj() {
let value = inputCpfCnpj.value.replace(/\D/g, '');
let mask = '';
if (value.length <= 3) {
mask = value;
} else if (value.length <= 6) {
mask = value.slice(0, 3) + '.' + value.slice(3);
} else if (value.length <= 9) {
mask = value.slice(0, 3) + '.' + value.slice(3, 6) + '.' + value.slice(6);
} else if (value.length <= 11) {
mask = value.slice(0, 3) + '.' + value.slice(3, 6) + '.' + value.slice(6, 9) + '-' + value.slice(9);
} else if (value.length === 12) {
mask = value.slice(0, 2) + '.' + value.slice(2, 5) + '.' + value.slice(5, 9) + '-' + value.slice(9, 12);
} else {
mask = value.slice(0, 2) + '.' + value.slice(2, 5) + '.' + value.slice(5, 8) + '/' + value.slice(8, 12) + '-' + value.slice(12);
}
inputCpfCnpj.value = mask;
}
inputCpfCnpj.addEventListener('input', handleInputCpfCnpj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment