Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save MauricioMoraes/2885d4975ac5e52d0ad7 to your computer and use it in GitHub Desktop.
Save MauricioMoraes/2885d4975ac5e52d0ad7 to your computer and use it in GitHub Desktop.
Mask for 8 or 9 digit phones in brazilian format with area code (ddd) - Using Jquery.inputmask plugin
// Using jquery.inputmask: https://github.com/RobinHerbots/jquery.inputmask
// For 8 digit phone fields, the mask is like this: (99) 9999-9999
// For 9 digit phone fields the mask is like this: (99) 99999-9999
function setupPhoneMaskOnField(selector){
var inputElement = $(selector)
setCorrectPhoneMask(inputElement);
inputElement.on('input, keyup', function(){
setCorrectPhoneMask(inputElement);
});
}
function setCorrectPhoneMask(element){
if (element.inputmask('unmaskedvalue').length > 10 ){
element.inputmask('remove');
element.inputmask('(99) 9999[9]-9999')
} else {
element.inputmask('remove');
element.inputmask({mask: '(99) 9999-9999[9]', greedy: false})
}
}
@MauricioMoraes
Copy link
Author

Este gist é para aqueles que já usavam o Jquery.inputmask e querem criar máscaras para número de telefone com 8 ou 9 dígitos mais o ddd no padrão brasileiro.

Exemplo de uso:

setupPhoneMaskOnField('#client-phone') // Passando o css-selector do input desejado
Input Output
1234567890 (12) 3456-7890
12345678900 (12) 34567-8900

Check out it in action in this fiddle

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