Matheus Souza Silva
Matheus Souza Silva

Reputation: 15

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.

Upvotes: 1

Views: 631

Answers (2)

German
German

Reputation: 1166

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>

Upvotes: 1

Dan
Dan

Reputation: 2705

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.

Upvotes: 1

Related Questions