emsifa / validasaur

Deno validation library
MIT License
45 stars 9 forks source link

NaN not handled properly? #33

Open ollipal opened 3 years ago

ollipal commented 3 years ago

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

Tandashi commented 2 years ago

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.