Máscara Telefone mudança para aceitar 9 digitos

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("(99) 9999-9999");

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?

Fala Fábio!
Tudo bem?

Eu também tive essa dúvida hoje, procurei a documentação e achei a resposta rapidamente
$("#telefone3").mask("(99) 9999-9999?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

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

Obrigado!

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

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

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 (99) 9999-99999 (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.

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

Se ainda precisar entre em contato.

Daniel Franco
falecomdanielfranco@gmail.com

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("(99) 9999-9999?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) != “") {
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) == "
”) {
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("(99) 9999-9999?9");
}

}

Posta a solução ai Daniel Franco!

Pra quem quiser, resolvi assim:

$('#telefone1')
        .mask("(99) 9999-9999?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("(99) 9999-9999?9");
            }
        });

Pessoal,

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

T+,
Mauricio

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("(99) 99999-9999"); } else { element.setMask("(99) 9999-9999"); } }) ;

Pessoal,

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

Fizemos desta forma.

$(’#telefone1’)
.mask("(99) 99999999?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("(99) 9999-9999?9");
}
});

Deêm uma olhada ai!!

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("(99) 9999-9999");
    }
})

Foi uma mão na roda, obrigado.

[quote=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("(99) 99999-9999"); } else { element.setMask("(99) 9999-9999"); } }) ;[/quote]

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

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:

/Função que padroniza telefone (11) 4184-1241 or (11) 93333-3333/
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;

}

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!

[code]$(function() {
$(’#telefone1’)
.mask("(99) 9999-9999?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("(99) 99999-9999");  
                } else if (novoTamanho === 10) {  
                    $elem.unmask();  
                    $elem.mask("(99) 9999-9999?9");  
                }
            }
        }, 1);
    });

});
[/code]

1 curtida

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) } } } };

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) } } } };