validasaur icon indicating copy to clipboard operation
validasaur copied to clipboard

NaN not handled properly?

Open ollipal opened this issue 5 years ago • 1 comments

I'd want to check in one validation that userInput is number and larger or equal to zero. To enable minNumber check, I need to convert the user input String to Number, with either parseInt()/parseFloat() (which return NaN for "") or Number() (which returns 0 for "" and hides the fact that the input was empty)

Code:

const userInput = "";
const test = parseFloat(userInput);
console.log(test);
console.log(isNaN(test));
console.log(await validate({ test }, { test: [required, notNull, isNumber, minNumber(0)] }));

Result

NaN
true
[ true, {} ]

So with this setup I'm not able to catch the empty user input.

The workaround is to validate both parsed and unparsed userInput, but I feel like notNull, isNumber or minNumber(0) should have failed the validation for NaN, or did I use validation somehow incorrectly? Or would it possible to have for example notNaN check (which I would be happy to contribute, if wanted)

I'm using version 0.15.0

ollipal avatar Dec 09 '20 18:12 ollipal

Would completely agree. Sadly NaN is considered a number in JavaScript so that's why isNumber, notNull and the first check of minNumber are not failing.

typeof NaN // 'number'

NaN is also not considered bigger, smaller, or equal to any other number hence also passing the second part of the minNumber check.

NaN < 0 // false
NaN > 0 // false
NaN === 0 // false

Would totally agree that at least minNumber should fail in case the provided value is NaN. Furthermore an additional notNaN check would be nice as well.

Tandashi avatar Oct 19 '22 10:10 Tandashi