Created
September 21, 2023 17:49
-
-
Save estevan-ulian/9ae8665ecb21a214fad24b647b92da17 to your computer and use it in GitHub Desktop.
Máscara para CNPJ
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
const inputCnpj = document.querySelector('.cnpj input'); | |
function handleInputCnpj() { | |
let value = inputCnpj.value.replace(/\D/g, ''); | |
let mask = ''; | |
if (value.length <= 2) { | |
mask = value; | |
} else if (value.length <= 5) { | |
mask = value.slice(0, 2) + '.' + value.slice(2); | |
} else if (value.length <= 8) { | |
mask = value.slice(0, 2) + '.' + value.slice(2, 5) + '.' + value.slice(5); | |
} else if (value.length <= 12) { | |
mask = value.slice(0, 2) + '.' + value.slice(2, 5) + '.' + value.slice(5, 8) + '/' + value.slice(8); | |
} else { | |
mask = value.slice(0, 2) + '.' + value.slice(2, 5) + '.' + value.slice(5, 8) + '/' + value.slice(8, 12) + '-' + value.slice(12); | |
} | |
inputCnpj.value = mask; | |
} | |
inputCnpj.addEventListener('input', handleInputCnpj); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment