Last active
May 24, 2023 01:10
-
-
Save fatecitu/c042575baf416947aa2b9306f17add82 to your computer and use it in GitHub Desktop.
Formatar RG com JS
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 formatarRG(campo) { | |
// Remove caracteres não numéricos | |
var rg = campo.value.replace(/\D/g, ''); | |
// Adiciona pontos e traço conforme o usuário digita | |
rg = rg.replace(/(\d{2})(\d)/, '$1.$2'); | |
rg = rg.replace(/(\d{3})(\d)/, '$1.$2'); | |
rg = rg.replace(/(\d{3})(\d{1,2})$/, '$1-$2'); | |
// Verifica se o último dígito é X e adiciona a string de retorno | |
if (campo.value.charAt(campo.value.length - 1).toUpperCase() === 'X') { | |
rg += '-X'; | |
} | |
// Atualiza o valor do campo | |
campo.value = rg; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment