Mask for CPF and CNPJ in the same field

37

Hello, I looked for this doubt in the questions, but I could not find it. Well, I would like to make a field have the masks of cpf and cnpj depending on the amount of characters typed. This is not quite true, because with several tests I did here, my code did not work that I need. I do not know if I should just change, or if I need to do another one.

Follow the code:

$("#cpfcnpj").keypress(function(){
    $("#cpfcnpj").unmask();
    var tamanho = $("#cpfcnpj").val().length;

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

Note: I'm using this plugin .

    
asked by anonymous 27.10.2015 / 19:40

5 answers

32

Try to use the greater or less equal operator, see below for an example.

$("#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");
    }

    // ajustando foco
    var elem = this;
    setTimeout(function(){
        // mudo a posição do seletor
        elem.selectionStart = elem.selectionEnd = 10000;
    }, 0);
    // reaplico o valor para mudar o foco
    var currentValue = $(this).val();
    $(this).val('');
    $(this).val(currentValue);
});
  

Example in JSFiddler: link

    
27.10.2015 / 19:55
17

In his documentation he already has an example that is: On -the-fly mask change , he used example with zip , just switch to CPF .

See the code below, how CPF and CNPF work in the same field:

var options = {
    onKeyPress: function (cpf, ev, el, op) {
        var masks = ['000.000.000-000', '00.000.000/0000-00'];
        $('.cpfOuCnpj').mask((cpf.length > 14) ? masks[1] : masks[0], op);
    }
}

$('.cpfOuCnpj').length > 11 ? $('.cpfOuCnpj').mask('00.000.000/0000-00', options) : $('.cpfOuCnpj').mask('000.000.000-00#', options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.js"></script>

<input class="cpfOuCnpj" value="11111111111" type="text">

Documentation: link

If you prefer in JSfiddle: link

Follow the discussion: link

    
25.04.2017 / 09:48
4

Are you using that Plugin? if Digitalbush Maskedinput is an example :

$(".hibridCpf").on('focusin',function(){
    var target = $(this);
    var val = target.val();
    target.unmask();
    val = val.split(".").join("");
    val = val.split("-").join("");
    val = val.split("/").join("");
    target.val(val);
});
$(".hibridCpf").on('focusout',function(){
    var target = $(this);
    var val = target.val();
    val = val.split(".").join("");
    val = val.split("-").join("");
    val = val.split("/").join("");
    if (val.length==11) {
        target.mask("999.999.999-99");
        target.val(val);
    } else {
        if (val.length==14) {
            target.mask("99.999.999/9999-99");
            target.val(val);
        } else {
            target.val('');
        }
    }
});
  

Try this example on jsfiddle .

This solution server also for ZIP Code fields where the user can enter a Brazilian or American Postal Code, using a similar logic ...

PS: A mascara plugin that I recommend and use is the Mask Plugin created by the Brazilian @ igorescobar (Github) , he put together Mask Input and Mask Money in one with more customization options , worth checking out!

There is also a simpler solution to your question posted by @rray question , but use another Plugin called Input Mask .

    
24.03.2017 / 18:13
3

The proposed solution does not work very well because the written Boolean condition may exhibit anomalies in the 'focusout' event.

I propose the following solution:

$(document).on('keydown', '[data-mask-for-cpf-cnpj]', function (e) {

    var digit = e.key.replace(/\D/g, '');

    var value = $(this).val().replace(/\D/g, '');

    var size = value.concat(digit).length;

    $(this).mask((size <= 11) ? '000.000.000-00' : '00.000.000/0000-00');
});

This solution is best in the following aspects:

  • The selector is working with the document as scope, that is, if the element is inserted after the DOM load is still functional.
  • Removes the need to use the 'setTimeout' function to adjust the selector.
  • Use the 'data-mask-for-cpf-cnpj' attribute to create a non-obstructive Javascript, which leaves the code clean, ie its element would look very elegant:

    eg <

  • 16.01.2018 / 21:20
    2

    That's how it worked for me. In%% of you remove the mask, in the focusin you apply the mask, removing the special masks.

    $(document).ready(function(e) {
      $(".cpfCnpj").unmask();
      $(".cpfCnpj").focusout(function() {
        $(".cpfCnpj").unmask();
        var tamanho = $(".cpfCnpj").val().replace(/\D/g, '').length;
        if (tamanho == 11) {
          $(".cpfCnpj").mask("999.999.999-99");
        } else if (tamanho == 14) {
          $(".cpfCnpj").mask("99.999.999/9999-99");
        }
      });
      $(".cpfCnpj").focusin(function() {
        $(".cpfCnpj").unmask();
      });
    });
    
        
    28.12.2017 / 14:02