valibot
valibot copied to clipboard
Decimal strings with `minValue("123.456")` or `maxValue`
I don't know what the right solution would be, but I would like to document this in this issue.
Decimal is usually a string, but validating it with minValue will do the string comparison, which is incorrect mentally. However if you forcibly cast the number to any, you can use the >= operator, which happens to work because of sloppy number handling of JS: "12.34" > 10 is true, "12.34" > 13 is false
import * as v from 'valibot';
// This type checks, but does not validate as a numeric value:
// const Schema = v.pipe(v.string(), v.decimal(), v.minValue("5"));
// This does not type check, but validates!
const Schema = v.pipe(v.string(), v.decimal(), v.minValue(5 as any));
const result1 = v.safeParse(Schema, "10");
const result2 = v.safeParse(Schema, "1");
console.log(result1, result2);
Of course, I could make my own minDecimalValue and maxDecimalValue, or check or transform the value to a number, or use this as any trick like above.
Ideally, JS would have the Decimal support, but that seems stuck in the TC39 process for now.
You can also transform it to a number before comparing it: v.pipe(v.string(), v.decimal(), v.transform(Number), v.minValue(5)) or allowing a number as an input to fix the TS issue:
import * as v from 'valibot';
const Schema = v.pipe(
v.union([v.pipe(v.string(), v.decimal()), v.number()]),
v.minValue(5),
);
We could change the type signature of minValue, but I'm afraid our users will end up with less secure code.
Hi, @Ciantic. I'm Dosu, and I'm helping the Valibot team manage their backlog and am marking this issue as stale.
Issue Summary:
- You reported that
minValueandmaxValuevalidators in Valibot perform string comparisons on decimal strings, leading to validation errors. - Fabian-hiller suggested workarounds such as transforming strings to numbers before validation or allowing numbers as input.
- Fabian-hiller expressed concerns about changing the
minValuetype signature due to potential security risks. - You acknowledged and appreciated the suggested workaround.
- The issue remains unresolved with no further updates.
Next Steps:
- Please let me know if this issue is still relevant with the latest version of Valibot by commenting here.
- If I don’t hear back within 30 days, I will automatically close this issue.
Thanks for your understanding and contribution!