Mask to validate CPF and CNPJ in the same field with jQuery

Asked

Viewed 8,628 times

3

I need to validate CPF and CNPJ in the same field with jQuery.

I tried this code I saw here on the site but it didn’t work:

$("#cpfcnpj").keydown(function(){
    try {
        $("#cpfcnpj").unmask();
    } catch (e) {}

    var tamanho = $("#cpfcnpj").val().length;

    if(tamanho < 11){
        $("#cpfcnpj").mask("999.999.999-99");
    } else if(tamanho >= 11){
        $("#cpfcnpj").mask("99.999.999/9999-99");
    }                   
});

Does anyone have any idea?

  • Did you put jQuery Masked Input in your solution as well? Without it, it won’t even work.

  • put yes, what is happening is the following, when I start typing it calls the mask, but the numbers do not leave the first field EX. x__..-__ (always q I type only the "x" changes and does not fill the whole field)

  • 6

    http://answall.com/questions/94956/m%C3%A1scara-para-Cpf-e-cnpj-no-mesmo-campo Same question

1 answer

2

There is an example in javascript that is easy to find on the internet, I’ve used in a project.
Javascript

function mascaraMutuario(o,f){
    v_obj=o
    v_fun=f
    setTimeout('execmascara()',1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function cpfCnpj(v){

    //Remove tudo o que não é dígito
    v=v.replace(/\D/g,"")

    if (v.length <= 14) { //CPF

        //Coloca um ponto entre o terceiro e o quarto dígitos
        v=v.replace(/(\d{3})(\d)/,"$1.$2")

        //Coloca um ponto entre o terceiro e o quarto dígitos
        //de novo (para o segundo bloco de números)
        v=v.replace(/(\d{3})(\d)/,"$1.$2")

        //Coloca um hífen entre o terceiro e o quarto dígitos
        v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2")

    } else { //CNPJ

        //Coloca ponto entre o segundo e o terceiro dígitos
        v=v.replace(/^(\d{2})(\d)/,"$1.$2")

        //Coloca ponto entre o quinto e o sexto dígitos
        v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3")

        //Coloca uma barra entre o oitavo e o nono dígitos
        v=v.replace(/\.(\d{3})(\d)/,".$1/$2")

        //Coloca um hífen depois do bloco de quatro dígitos
        v=v.replace(/(\d{4})(\d)/,"$1-$2")

    }

    return v
}

Using

<html>
  <head>
    <title>Máscara Javascript de CNPJ e CPF no Mesmo Campo do Formulário</title>
  </head>
  <body>
    <form>
      <input type='text' name='cpfcnpj' onkeypress='mascaraMutuario(this,cpfCnpj)' onblur='clearTimeout()'>
    </form>
  </body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.