Limit characters to an amount "x" with javascript

Asked

Viewed 75 times

-3

I am adding a mask and only allowing numbers in a function in a React application, but I also want to limit the characters typed inside the input, however I am not succeeding, someone could help me with this question, I thank you already.

Follow the code js:

const mascaraCPF = () =>{
            const valorInput = document.querySelector('#filtroFuncionario')
            valorInput.addEventListener('input', () =>{
                const i = valorInput.value.length
                const str = valorInput.value
                if(isNaN(Number(str.charAt(i-1)))){
                    valorInput.value = str.substring(0, i-1)
                }
            })
            document.addEventListener('keydown', (e) => { 
                if(e.keyCode != 46 && e.keyCode != 8){
                    const valorInputLen = document.getElementById("filtroFuncionario").value.length
                    var max_len = 14;
                    if (valorInputLen === 3 || valorInputLen === 7)
                    document.getElementById("filtroFuncionario").value = document.getElementById("filtroFuncionario").value + "."
                    else if (valorInputLen === 11) 
                    document.getElementById("filtroFuncionario").value = document.getElementById("filtroFuncionario").value + "-"
                    if(valorInputLen >= max_len){
                        const filtro = document.getElementById("filtroFuncionario").value
                        const filtroSub = filtro.substring(0,14)
                        filtroSub.replace(filtroSub, '')
                        console.log(  filtroSub.replace(filtroSub, ''))
                    }
                }
            });
        }
        mascaraCPF()
  • Have you tried <label>CPF:<input id="filtroFuncionario" type="text" maxlength="14"></label>

1 answer

0

I believe that you are approaching the problem in the wrong way, it is possible to limit the number of digits in the 'input' in a much simpler and local way.

Follows a functional code (JS vanilla/pure).

var cpf_input;

var cpf;

function input_check(){

if(document.querySelector('#input').value.length < 11) // sendo 11 o número máximo de caracteres permitidos dentro do input, pode ser contido dentro de uma variável.
{cpf = document.querySelector('#input').value}

else{document.querySelector('#input').value = cpf}
}
<input id='input' onkeyup='input_check()'>

Browser other questions tagged

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