Format mask for CNPJ

4

I need to format a mask for CNPJ. Until then it is done, but the company default is to format with space instead of point.

This is the code I am using.

valorDoTextBox = valorDoTextBox.replace(/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3")

Someone can explain to me how this part (/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3") works so you can take the stitches and put a space.

Thank you for being able to help me.

function MascaraParaLabel(valorDoTextBox) {

        if (valorDoTextBox.length <= 14) {  

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

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

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

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

I pass the value of the unformatted textbox 14397462000109 and the label at the front shows 14 397 462 / 0001-09 formatted in the company standard.

    
asked by anonymous 30.07.2015 / 21:15

2 answers

8

To format at once, you can do it this way:

"14397462000109".replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, "$1 $2 $3/$4-$5")

This will result in 14 397 462/0001-09 .

Now, if you use an input mask when typing, you can use something like:

$("input").on("keyup", function(e)
{
    $(this).val(
        $(this).val()
        .replace(/\D/g, '')
        .replace(/^(\d{2})(\d{3})?(\d{3})?(\d{4})?(\d{2})?/, "$1 $2 $3/$4-$5"));
});

Fiddle

The difference in regex is that I left the second group on as optional, adding the ? after each one. It is not a perfect input mask, but you can improve it by limiting other characters etc.

    
31.07.2015 / 13:46
-2

@Sergio

Hello. It has no global variable. Here is an example, you can make changes if you do not respond. Where has "cpf points", I put "space".

obj = o; //variavel recebe o//
fun = f; //variavel recebe f//
setTimeout("execMascara()", 1);
}

function execMascara() {
    obj.value = fun(obj.value);
}

function cpf(cpf) {
    mascara = cpf.replace(/\D/g, "");
    mascara = cpf.replace(/(\d{3})(\d)/, "$1 $2");
    mascara = cpf.replace(/(\d{3})(\d)/, "$1 $2");
    mascara = cpf.replace(/(\d{3})(\d)/, "$1 $2");

    return mascara;
}

In the form:

<label="cpf">
CPF: <input onkeypress="mascara(this, cpf)" maxlength="14"/>
</label>
    
31.07.2015 / 16:58