joi
joi copied to clipboard
Parsing number incorrectly flagged as unsafe
Support plan
- is this issue currently blocking your project? (no):
- is this issue affecting a production system? (yes):
Context
- node version: 16.6.1
- module version with issue: 17.4.2
- last module version without issue: unknown
- environment (e.g. node, browser, native): node
- used with (e.g. hapi application, another framework, standalone, ...): standalone
- any other relevant information:
What are you trying to achieve or the steps to reproduce?
Validating and parsing a value from a string to a number. Specifically, the value "873.19999999999993". The result of the validator is that the field value is "unsafe". We have been able to work around this issue by using the unsafe() flag, however the documentation for the unsafe() flag notes that it is to be used to work around numbers that are outside of the Min/Max JavaScript Number range (which this number is not).
const schema = Joi.object({
value: Joi.number().positive().optional(),
});
const submission = {
value: '873.19999999999993',
};
const result = schema.validate(submission);
expect(result.error).toBeUndefined();
What was the result you got?
Received: [ValidationError: "value" must be a safe number]
What result did you expect?
The test to pass and parse the number as a valid/safe number
I believe that this is a floating number problem instead of a joi problem though.
the term "Safe Number" here actually means "Safe Integer", when it comes to floating point, tl;dr is that the more precision you have, the chances of converting from string to number resulting in the number not being the number you expect is higher.
try doing Number.parseFloat('873.19999999999993')
and you'll see why.