Skip to content

Instantly share code, notes, and snippets.

@lucascaires
Last active June 4, 2018 20:20
Show Gist options
  • Save lucascaires/23245342b4c9c21f2efeb1d135d574a9 to your computer and use it in GitHub Desktop.
Save lucascaires/23245342b4c9c21f2efeb1d135d574a9 to your computer and use it in GitHub Desktop.
Código simples para máscara de telefones brasileiros com 9 ou 8 dígitos
;(function() {
const phones = document.querySelectorAll('[type=tel]');
[].forEach.call(phones, function(phone) {
phone.addEventListener('keyup', function(k){
this.setAttribute('maxlength', 15);
let a = this.value;
a = a.replace(/\D/g, "");
a = a.replace(/^(\d{2})(\d)/g, "($1) $2");
if (a.length > 12) a = a.replace(/(\d)(\d{4})$/, "$1-$2");
this.value = a;
});
});
})();
@lucascaires
Copy link
Author

Só colar em qualquer parte de sua página e todos os seus inputs do tipo "tel" irão ficar com máscara.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment