Home > database >  Deleting a negative value from number input and validation
Deleting a negative value from number input and validation

Time:03-21

I feel that this is a dumb question, sorry.

I have an input with the number type and I want to add some validation to it. It is not required, so an empty string should be valid, negative numbers too, but not the - sign.

Consider now I've entered -102 into that field and removing symbols one by one, watching for changes.

Here's the basic codepen for it. As you can see, when there's just a - sign left the value (event.target.value) is an smpty string, which should be valid.

So, how can I check if there is only a minus sign left and mark this field as invalid?

const el = document.getElementById('input');

el.addEventListener('keyup', (e) => {
  const value = e.target.value;
  console.log(value)
})
<input type="number" id="input">

CodePudding user response:

you can use pattern to only accept positive or negative number

in JS you can call method checkValidity() or use {yourinput}.validity.valid to check if value entered in input is valid or not

in css you can use the pseudo class :invalid to design your input when value entered don't match the pattern/field expectation

const el = document.getElementById('input');

el.addEventListener('keyup', (e) => {
  console.log(el.checkValidity());
  if (!el.checkValidity()) {
    //treat case input invalid
  }
})
input:invalid {
 color: red;
}
<input type="number" id="input" pattern="\d ">

  • Related