2

On my webpage there is an input box that should only allow user to enter a positive int/float number (i.e. 1234, 123.4, 12.34, 1.234 should all be allowed).

To make sure the value is valid, I have a function to validate the value before sending it to the server:

function isPositiveFloat(s){
    return String(Number(s)) === s && Math.floor(Number(s)) > 0;
}

The function works great expect for one scenario: isPositiveFloat(1.0) will return false, as it turns out Number(1.0) will convert it to 1, therefore made the validation failed.

Any suggestions on how should I resolve this issue? Is using regex the only way to go?

Thanks in advance for any help!

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Eliellel
  • 1,426
  • 1
  • 9
  • 14

1 Answers1

2

You just need to use !isNaN(s)along with Number(s)>0:

function isPositiveFloat(s) {
  return !isNaN(s) && Number(s) > 0;
}

Demo:

function isPositiveFloat(s) {
  return !isNaN(s) && Number(s) > 0;
}
<input type="text" onchange="console.log(isPositiveFloat(this.value))" />

You can check on the MDN reference of isNaN() examples that:

isNaN('37.37'); // false: "37.37" is converted to the number 37.37 which is not NaN

So as you can see it will be working in your case with float numbers.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78