Mask for CPF or CNPJ without using plugins

0

I managed to make simple masks for phone fields, zip codes, etc., etc. But I wanted a mask to automatically detect and format a field for CPF or CNPJ in the same input, but that was preferably pure html / javascript, with no plugins at most using a radio button or dropdown as a conditional.

Is it possible to do this without using any plugins or am I asking too much?

Adding: I know the subject is quite repetitive, and I even found a lot of documentation about it, but always using external plugins, I would like to be able to do something totally portable, that does not need additional files and that works offline. >

I made the generic mascara using the following function:

function formatar(mascara, documento){
var i = documento.value.length;
var saida = mascara.substring(0,1);
var texto = mascara.substring(i)
if (texto.substring(0,1) != saida){
documento.value += texto.substring(0,1);

and later on the inputs the events: onkeypress="formatar('###.###.###-##', this)" e etc

I wanted a function or script that would detect the number of digits entered to configure the mask as a CPF or CNPJ.

    
asked by anonymous 22.02.2018 / 19:11

1 answer

2

Try these masks using regex.

function formatarCampo(campoTexto) {
    if (campoTexto.value.length <= 11) {
        campoTexto.value = mascaraCpf(campoTexto.value);
    } else {
        campoTexto.value = mascaraCnpj(campoTexto.value);
    }
}
function retirarFormatacao(campoTexto) {
    campoTexto.value = campoTexto.value.replace(/(\.|\/|\-)/g,"");
}
function mascaraCpf(valor) {
    return valor.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g,"\.\.\\-\");
}
function mascaraCnpj(valor) {
    return valor.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/g,"\.\.\\/\\-\");
}
<input type="text" onfocus="javascript: retirarFormatacao(this);" onblur="javascript: formatarCampo(this);" maxlength="14"/>
    
22.02.2018 / 19:57