Máscara Telefone mudança para aceitar 9 digitos

20 respostas
fabio.cbrandao

E ai Gujs.

Como todos já sabem está pra acontecer a mudança no meio do ano onde os números de telefone de São Paulo vão ganhar um digito a mais resumindo fu… nossos sites que possuem cadastro de telefone… brincadeira…

Então vamos lá eu atualmente utilizo o MaskedInput do JQuery e utilizo a seguinte máscara:

$("#telefone").mask("([telefone removido]");

Porém ele inclui a máscara MAS… se eu aumentar um digito nessa máscara ele considera todos obrigatórios e no meu formulário vai poder entrar tanto telefones de 8 digitos como telefone de 9 digitos eu gostaria q 1 UM digito apenas não fosse obrigatório.

E ai vcs já estão arrumando seus formulários já fizeram algo do tipo?

20 Respostas

A

Fala Fábio!
Tudo bem?

Eu também tive essa dúvida hoje, procurei a documentação e achei a resposta rapidamente
$("#telefone3").mask("([telefone removido]?9");

Tudo o que for postado depois do ? é opcional ao usuário!
Então fica bem fácil :slight_smile:

Espero ter ajudado! :wink:
Abraços,
Junior

A

Vou testar isso na minha aplicação e posto aqui meu feedback!!!

Obrigado!

RiQuInHo_

Logo mais vai ser ‘10’ já é bom se preparar cedo rs

fabio.cbrandao

Ai galera meu formulário funcionou e está pronto pra receber o novo padrão de 9 digitos

kaisari

Estava procurando um local para discutir esse assunto, e parece que aqui é o ideal.
Tenho que fazer a correção para diversos sites que gerencio, e a solução apresentada também me veio a mente de imediato. O problema é que sou chato (hehehe) e ao pesquisar descobri que o padrão de formato adotado pela Anatel é (99) 99999-9999 e não ([telefone removido]9 (prefixo vai ficar com 5 dígitos). Parece bobeira mas… é para isso que usamos a máscara, para seguir o padrão pré-estabelecido.
Ainda não tenho a resposta, mas estou rascunhando… assim que tiver algo concreto posto aqui.

D

Olá, criei uma solução para esse problema.

Se ainda precisar entre em contato.

Daniel Franco
[email removido]

A

Olá pessoal, desenvolvi uma solução que atende tanto os números de celulares antigos como os novos (9 digitos).

$(document).ready(function () {

$(input[id*=TelefoneContato]).mask("([telefone removido]?9");

$(input[id*=TelefoneContato]).focusout(function () {

$(input[id*=TelefoneContato]).val(Mascara($(input[id*=TelefoneContato]).val()));

$(input[id*=TelefoneContato]).val(strTelefone);

});

});

var strTelefone = “”;

function Mascara(objeto) {

if (objeto.substring(14,15) != <em>") {

var strAntesDelimitador = objeto.substring(0, 9);

var strDepoisDelimitador = objeto.substring(10, 11);

var delimitador = objeto.substring(9, 10);

var strRestante = objeto.substring(11);

strTelefone = strAntesDelimitador + strDepoisDelimitador + delimitador + strRestante;

$(input[id*=TelefoneContato]).unmask();

$(input[id*=TelefoneContato]).mask("(99) 99999-999?9");

}

else if (objeto.substring(14, 15) == "</em>”) {

var strAntesDelimitador = objeto.substring(0, 9);

var strDepoisDelimitador = objeto.substring(9, 10);

var delimitador = objeto.substring(10, 11);

var strRestante = objeto.substring(11,14);

strTelefone = strAntesDelimitador + delimitador + strDepoisDelimitador + strRestante;

$(input[id*=TelefoneContato]).unmask();

$(input[id*=TelefoneContato]).mask("([telefone removido]?9");

}

}

michellhornung

Posta a solução ai Daniel Franco!

michellhornung

Pra quem quiser, resolvi assim:

$('#telefone1')
        .mask("([telefone removido]?9")
        .live('focusout', function (event) {
            var target, phone, element;
            target = (event.currentTarget) ? event.currentTarget : event.srcElement;
            phone = target.value.replace(/\D/g, '');
            element = $(target);
            element.unmask();
            if(phone.length &gt; 10) {
                element.mask("(99) 99999-999?9");
            } else {
                element.mask("([telefone removido]?9");
            }
        });
mhnagaoka

Pessoal,

fiz um jsfiddle com a solução do michellhornung.
http://jsfiddle.net/vccmk/3/

T+,
Mauricio

D

Resolvi assim para o caso do jquery meio mask.

$("[alt=phone]").live('keypress', function (event) { var target, phone, element; target = (event.currentTarget) ? event.currentTarget : event.srcElement; phone = target.value.replace(/\D/g, ''); element = $(target); element.unsetMask(); if (phone.length > 5 && phone.substr(0,3) == "119") { //ele só vai colocar no formato de SP quando for ddd 11 e iniciar com 9. element.setMask("([telefone removido]"); } else { element.setMask("([telefone removido]"); } }) ;

anderson.silva

Pessoal,

Na empresa em que eu trabalho tivemos hoje esta solicitação, meio tarde por sinal. rss

Fizemos desta forma.

$(’#telefone1)

.mask("([telefone removido]?9")

.live(focusout, function (event) {

var target, phone, element;

target = (event.currentTarget) ? event.currentTarget : event.srcElement;

phone = target.value.replace(/\D/g, ‘’);

element = $(target);

element.unmask();

if(phone.length > 10) {

element.mask("(99) 99999-999?9");

} else {

element.mask("([telefone removido]?9");

}

});

Deêm uma olhada ai!!

R

Danilo, gostei da sua solução, mas como o prefixo dos celulares de S. Paulo vai de 6###.#### a 9###.####, e não apenas 9###.####, alterei um pouco o seu código para acomodar todos eles:

$("[alt=phone]").live('keypress', function (event) {
    var target, phone, element;
    target = (event.currentTarget) ? event.currentTarget : event.srcElement;
    phone = target.value.replace(/\D/g, '');
    element = $(target);
    element.unsetMask();
    if (phone.length > 5 && phone.substr(0,3) > "115"   && phone.substr(0,3) <= "119") { //ele só vai colocar no formato de SP quando for ddd 11 e iniciar entre 6 e 9.
        element.setMask("(99) 999-999-999");
    } else {
        element.setMask("([telefone removido]");
    }
})

Foi uma mão na roda, obrigado.

Danilo MR:
Resolvi assim para o caso do jquery meio mask.

$("[alt=phone]").live('keypress', function (event) { var target, phone, element; target = (event.currentTarget) ? event.currentTarget : event.srcElement; phone = target.value.replace(/\D/g, ''); element = $(target); element.unsetMask(); if (phone.length > 5 && phone.substr(0,3) == "119") { //ele só vai colocar no formato de SP quando for ddd 11 e iniciar com 9. element.setMask("([telefone removido]"); } else { element.setMask("([telefone removido]"); } }) ;

ErickRAR

Altere de novo pois em breve será para o Brasil todo. :wink:

R

Pois é, Erick, mas é o tipo de alteração que, infelizmente, vamos ter que fazer on the fly, à medida em que a Anatel for determinando… :thumbdown:

P

/Função que padroniza telefone ([telefone removido] or ([telefone removido]/
function Telefone(v) {

v = v.replace(/\D/g, "");
v = v.replace(/^(\d\d)(\d)/g, "($1) $2");

if (v.length < 14) {
    v = v.replace(/(\d{4})(\d)/, "$1-$2");
} else {
    v = v.replace(/(\d{5})(\d)/, "$1-$2");
}   

return v;

}

Fi1

Olá pessoal,

Fiz algumas modificações nas versões mostradas para permitir que a máscara mude enquanto se digita, não somente quando se sai do campo.

http://jsfiddle.net/vccmk/634/

O motivo do setTimeout é pq, do contrário, não temos acesso ao texto atualizado, somente o texto antigo (1 caractere a menos). O motivo do keydown em vez de keypress é pq keypress não pega backspace.

O único defeito que eu encontrei foi quando a pessoa está com 11 dígitos e apaga mais de um caractere de uma vez. Aí ele só vai atualizar a máscara quando chegar no décimo dígito.

[]s!

$(function() {
    $('#telefone1')  
        .mask("([telefone removido]?9")  
        .keydown(function() {
            var $elem = $(this);
            var tamanhoAnterior = this.value.replace(/\D/g, '').length;
            
            setTimeout(function() { 
                var novoTamanho = $elem.val().replace(/\D/g, '').length;
                if (novoTamanho !== tamanhoAnterior) {
                    if (novoTamanho === 11) {  
                        $elem.unmask();  
                        $elem.mask("([telefone removido]");  
                    } else if (novoTamanho === 10) {  
                        $elem.unmask();  
                        $elem.mask("([telefone removido]?9");  
                    }
                }
            }, 1);
        });
});
J

A seguir. Somente números + DDD + tel 8 “OU” 9 dígitos + tratamento para “ç e Ç”

By: ??Falcão??

js: Assinatura(NomeCampo)

function telefone(a) { $(a).keyup(function (f) { if ((f.keyCode > 64 && f.keyCode < 91) || f.keyCode == 186) { var d = (String.fromCharCode(f.keyCode)).toUpperCase(); var c = (a.value.charAt(a.value.length - 1)).toUpperCase(); if (d == c || c == “Ç” || c == “ç”) { a.value = a.value.substring(0, (a.value.length - 1)) } } }); separador = “(”; separador1 = “)”; separador2 = “-”; conjunto1 = 0; conjunto2 = 3; conjunto3 = 8; if (a.value.length < 13) { if (a.value.length == conjunto1) { a.value = a.value + separador } if (a.value.length == 4 && a.value.indexOf(")") == -1) { a.value = a.value.substring(0, 3) + separador1 + a.value.substr(3, 1) } if (a.value.length == conjunto2) { $(“html”).keyup(function (b) { if (b.keyCode == 8) { } else { if (a.value.length == conjunto2) { a.value = a.value + separador1 } } }) } } if (a.value.length == 13 && a.value.indexOf("-") == 9) { a.value = a.value.replace("-", “”); a.value = a.value.substring(0, 8) + separador2 + a.value.substr(8, 4) } else { if (a.value.length == 12) { a.value = a.value.replace("-", “”); a.value = a.value.substring(0, 8) + separador2 + a.value.substr(8, 4) } else { if (a.value.length > 13) { a.value = a.value.replace("-", “”); a.value = a.value.substring(0, 9) + separador2 + a.value.substr(9, 4) } } } };

J

A seguir. Somente números + DDD + tel 8 “OU” 9 dígitos + tratamento para “ç e Ç”

By: ??Falcão??

js: Assinatura(NomeCampo)

function telefone(a) { $(a).keyup(function (f) { if ((f.keyCode > 64 && f.keyCode < 91) || f.keyCode == 186) { var d = (String.fromCharCode(f.keyCode)).toUpperCase(); var c = (a.value.charAt(a.value.length - 1)).toUpperCase(); if (d == c || c == “Ç” || c == “ç”) { a.value = a.value.substring(0, (a.value.length - 1)) } } }); separador = “(”; separador1 = “)”; separador2 = “-”; conjunto1 = 0; conjunto2 = 3; conjunto3 = 8; if (a.value.length < 13) { if (a.value.length == conjunto1) { a.value = a.value + separador } if (a.value.length == 4 && a.value.indexOf(")") == -1) { a.value = a.value.substring(0, 3) + separador1 + a.value.substr(3, 1) } if (a.value.length == conjunto2) { $(“html”).keyup(function (b) { if (b.keyCode == 8) { } else { if (a.value.length == conjunto2) { a.value = a.value + separador1 } } }) } } if (a.value.length == 13 && a.value.indexOf("-") == 9) { a.value = a.value.replace("-", “”); a.value = a.value.substring(0, 8) + separador2 + a.value.substr(8, 4) } else { if (a.value.length == 12) { a.value = a.value.replace("-", “”); a.value = a.value.substring(0, 8) + separador2 + a.value.substr(8, 4) } else { if (a.value.length > 13) { a.value = a.value.replace("-", “”); a.value = a.value.substring(0, 9) + separador2 + a.value.substr(9, 4) } } } };

K

Pessoal nao sei se vcs estao precisando ainda desta função porem precisei alterar um sistema que desenvolvo em ASP pois la tem um campo telefone de recados, logo ele pode ser tanto fixo como celular entao adaptei esta função para formatar de acordo com os numeros digitados.
Logo se encontrar na string o numero 9 logo apos o DDD significa que é um celular senão é um tel fixo.

Caso queiram permitir que se o primeiro numero digitado for 6-7-8 tambem formate com 5 caracteres o pre-fixo é só descomentar a linhas em Azul e comentar a linha em vermelho.
se precisarem esta ae para ajudar o pessoal grato.

Criado 29 de fevereiro de 2012
Ultima resposta 19 de nov. de 2013
Respostas 20
Participantes 16