'Nullable string with min/max range using Yup validation
I have found that yup ignores the nullable field when there is a min/max value added.
myValue: string().nullable().min(10, "This value must be minimum of 10 characters.")`.
There was an issue that was closed on the repo without any solution given.
Is this expected behaviour, and if so are there any workarounds? I could check the length of the value without using yup and raise an error, however would prefer to keep it all within the yup schema validation.
Solution 1:[1]
Had this exact issue today and was surprised to not see more discussion on it.
Based on Raz's answer to a similar question here, I believe this happens because an empty string is not treated as null in yup, and so the min / max validation runs.
I'd suggest transforming the empty string to null as part of the validation as below:
myValue: string().nullable().transform((o, c) => o === "" ? null : c).min(10, "This value must be minimum of 10 characters.").
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dan Rushton |
