yup: yup.number().nullable() does not allow `null` value
const quantity = number().positive().nullable(); does not work for me in case of quantity:null this input gives me this error
quantity must be a
numbertype, but the final value was:NaN(cast from the valueNaN). ValidationError: quantity must be anumbertype, but the final value was:NaN(cast from the valueNaN).
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 12
- Comments: 22 (1 by maintainers)
Hey, you must pass a boolean value as argument to
nullableI used:
…after noting that
transformsupplies two arguments to the callback, the second being theoriginalValuewhich was the empty string for me.I solved this problem like this:
Hi guys,
Why is this issue closed.
The simple fact that clearing an input field with
type="number"should not throw an “Invalid value” message as @simoami showed.Why should we have to use a
transformmethod to fix this everytime we have a number field ?I have the same problem. nullable() is the same as nullable(true), so that’s not the solution.
So is this going to be fixed/changed? null, undefined, NaN should trigger the validation only if nullable(false) or required() is present … and i would like to avoid adding that transform to each number input…
Also validating the NaN in case of numeric inputs
If you check the original validation error, it has a property called
paramswhich should contain something like:originalValueshould contain the original … value that was passed before Yup tried to cast it to number. Are you sure that what you’re passing (asoriginalValue) when usingnullable(true)is in factnull? I work on a project which has all types as nullable (including number) and it works well as expected.I did encounter the issue when a value coming from an input was empty string (which is, of course
NaN). If it happens that you want certain values such as empty string to be considerednull, you can usetransformfirst, something like:In which case, if
nullable(true), then empty strings would also be valid. Otherwise, empty string would be transformed tonullbut fail ifnullable(false)Perhaps you can borrow from the
.default(...)value when a cast doesn’t work. So.default(undefined)would return the same for empty string and.default(0)would return 0 for an empty string.Additionally, you can see how this error is nasty, (using yup and formik), which is why I came to post about it.
@simoami the way I was dealing with it was:
I think the above makes sense (number.js:19) in that, we wouldn’t always want default to
0when it’s an empty string. In my use case, an empty string (from input field) meantundefinedand not0Were you able to fix this? I am also dealing with this issue.
If the schema passes the validation I would expect the same value be also castable via the schema.
This isn’t the case right now.