Skip to content

Instantly share code, notes, and snippets.

@tiagocordeiro
Created January 12, 2018 14:43
Show Gist options
  • Save tiagocordeiro/7c7ac50f7f8b78fe6909a80072fe2c9d to your computer and use it in GitHub Desktop.
Save tiagocordeiro/7c7ac50f7f8b78fe6909a80072fe2c9d to your computer and use it in GitHub Desktop.
Mascara para telefones no formato brasileiro (com 8 ou 9 dígitos)
<script>
function mascaraTelefone( campo ) {
function trata( valor, isOnBlur ) {
valor = valor.replace(/\D/g,"");
valor = valor.replace(/^(\d{2})(\d)/g,"($1)$2");
if( isOnBlur ) {
valor = valor.replace(/(\d)(\d{4})$/,"$1-$2");
} else {
valor = valor.replace(/(\d)(\d{3})$/,"$1-$2");
}
return valor;
}
campo.onkeypress = function (evt) {
var code = (window.event)? window.event.keyCode : evt.which;
var valor = this.value
if(code > 57 || (code < 48 && code != 8 )) {
return false;
} else {
this.value = trata(valor, false);
}
}
campo.onblur = function() {
var valor = this.value;
if( valor.length < 13 ) {
this.value = ""
}else {
this.value = trata( this.value, true );
}
}
campo.maxLength = 14;
}
</script>
<!-- Entrar com o Formulário aqui -->
<script>
mascaraTelefone( gform_2.input_4 ); // Alterar o ID do form e NAME do input
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment