Created
January 12, 2018 14:43
-
-
Save tiagocordeiro/7c7ac50f7f8b78fe6909a80072fe2c9d to your computer and use it in GitHub Desktop.
Mascara para telefones no formato brasileiro (com 8 ou 9 dígitos)
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
<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