Format mask for CNPJ
I need to format a mask for CNPJ. Until then it is done, but the company's default is to format with space instead of point.
This is the code I'm using.
valorDoTextBox = valorDoTextBox.replace(/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3")
Can someone explain me with works this part (/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3")
so I can take the point and put a space.
Thank you for helping 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 textbox without formatting 14397462000109 and the label that is in front, shows 14 397 462/0001-09 formatted in company Standard.
3 answers
I made this code, I thought it was simple.
document.getElementById('produto-1-cnpj').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,2})(\d{0,3})(\d{0,3})(\d{0,4})(\d{0,2})/);
e.target.value = !x[2] ? x[1] : x[1] + '.' + x[2] + '.' + x[3] + '/' + x[4] + (x[5] ? '-' + x[5] : '');
});
<input id="produto-1-cnpj" class="form-control rounded-form" type="text" placeholder="Insira o CNPJ da sua loja" maxlength="18"/>
To format at once, you can do this:
"14397462000109".replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, "$1 $2 $3/$4-$5")
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"));
});
The difference in the regex is that I left the second group onwards as optional, adding the ?
after each one. It's not a perfect input mask, but you can improve it by limiting other characters etc.
@ Sergio
Hello. It has no global variable. Here's an example, you can make changes if you don't. Where it has "the points of the cpf", 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>