Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
Unable to delete text from input after adding regex to it

I've this javascript code:

document.querySelector('div[data-field-name="CNPJ"] input').addEventListener('keydown', (inheritance) => {
        let value = inheritance.target.value;
        console.log(value.length)
        if (value.length >= 18) {
            inheritance.preventDefault()
            inheritance.stopPropagation()
            return
        }
        value = value.replace(/\D/g, "")
        value = value.replace(/^(\d{2})(\d)/, "$1.$2")
        value = value.replace(/^(\d{2}).(\d{3})(\d)/, "$1.$2.$3")
        value = value.replace(/.(\d{3})(\d)/, ".$1/$2")
        value = value.replace(/(\d{4})(\d)/, "$1-$2")
        inheritance.target.value = value;
    })

The problem that I'm having is when the input's value reach the maximum length (I stipulated in the code), I'm unable to delete the text.

I don't know what is causing this issue.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are preventing default input behaviour in this line when you reach the max length. Remove it and add a maxlength check in the HTML code instead.

  if (value.length >= 18) {
      inheritance.preventDefault()
      inheritance.stopPropagation()
      return
  }

I am not sure why this line is required since you can do something similar in HTML:

<input maxlength="18"></input>

Can you elaborate why maxlength has to be done in JavaScript?

Alternatively you can add a Backspace or similar key checks in your logic:

if (
    value.length >= 18
    && inheritance.key !== "Backspace"
  ) {
    inheritance.preventDefault()
    inheritance.stopPropagation()
    return
}

I don't recommend detecting specific keys personally since HTML considers a lot more edge cases than a single key check will.

Check out the MDN doc on input pattern.

about 4 years ago · Juan Pablo Isaza Relatório

0

There is no way for the previous implementation cause inheritance.preventDefault() makes the function not to produce an input when the length is greater than or equal to 18

The better way is to scratch that if statement then add maxlength="18" attribute to the input element.

See the demo :

That was because of the if statement

document.querySelector('div[data-field-name="CNPJ"] input').addEventListener('keydown', (e) => {
  let value = e.target.value;
  value = value.replace(/\D/g, "")
  value = value.replace(/^(\d{2})(\d)/, "$1.$2")
  value = value.replace(/^(\d{2}).(\d{3})(\d)/, "$1.$2.$3")
  value = value.replace(/.(\d{3})(\d)/, ".$1/$2")
  value = value.replace(/(\d{4})(\d)/, "$1-$2")
  e.target.value = value;
})
<div data-field-name="CNPJ">
  <input type="text" maxlength="18" />
</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda