1

I found this neat solution to my negative numbers problem https://stackoverflow.com/a/46039201

Here it is below

onInput={(e)=>{
 e.target.value = !!e.target.value && Math.abs(e.target.value) >= 0 ? Math.abs(e.target.value) : null;
}}

But I have a bit of an issue it only allows numbers and I do require decimal places because these inputs are for currencies such as activation fee, billing amount and such. Otherwise than that the above solution works like a charm

Does anyone here have a similar solution or something that can be added to this to make it accept decimal places ?

Ive tried looking into some others but then the user can type in -1111 and it saves it even if you add min={0} to the input field

Faziki
  • 767
  • 1
  • 9
  • 24
  • You can try to use `regex` to do it – Ian Jun 06 '22 at 10:11
  • @Ian Ive tried that and it still allows -1111 numbers – Faziki Jun 06 '22 at 10:16
  • 1
    Valid input checking on the `input` event is not really a great idea, especially as you update the input, as you have found out. To save you lots of headaches, just do it the proper way, and check your data on submit. Otherwise you have issues like as you type you get `1`, `1.`, is `1.` valid?, the user was only trying to type `1.1`.. etc. If you want to show validity as you type, that's not as bad, but updating as you type is generally clunky.. – Keith Jun 06 '22 at 10:22

2 Answers2

1

It wasn't easy for me to find a solution. In the end, what worked was a combination of a pattern and a custom attribute to store the previous value:

const restricted = document.querySelector('#restricted')
restricted.addEventListener('keyup', event => {
  const value = event.target.value;
  if (!/^[0-9]+\.?[0-9]?$/.test(value) && value !== '') {
    event.target.value =  event.target.getAttribute('data-value');
  } else {
    event.target.setAttribute('data-value', value);
  }
});
<input id="restricted">
  • This method won't always work on a `type="number"` input. FireFox for example allows users to type non numeric characters but they are not read into the value by key events and so remain in the input field, invalidating its value. It's an adequate solution for generic inputs but has to be balanced against the loss of the several useful features associated with `type=number`. – Dave Pritlove Jun 06 '22 at 11:42
  • @DavePritlove that's the reason why I didn't use `type="number"`. Yes, it provides a lot of useful features, the number keyboard on mobile devices above all, but a solution that works with bot uncancelable events and `type="number"` is impossible right now – Christian Vincenzo Traina Jun 06 '22 at 12:12
0

Make use of step

<input type="number" min="0" step="0.1" oninput="this.value = Math.abs(this.value)">