Home > database >  Allowing only positive numbers with decimal places
Allowing only positive numbers with decimal places

Time:06-07

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

CodePudding user response:

Make use of step

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

CodePudding user response:

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">

  • Related