I'm trying to implement a quite basic validation for a form field/select. Validation schema:
vehicleProvider: Yup.object() // This is an object which is null by default
.required('formvalidation.required.message')
.nullable(),
reserveVehicle: Yup.number().when('vehicleProvider', { // This is a number which is null by default
is: provider => provider?.hasReserve,
then: Yup.number()
.required('formvalidation.required.message')
.nullable(),
otherwise: Yup.number().notRequired()
}),
What I want to do: Only require/validate reserveVehicle
if provider.hasReserve
is true
. Otherwise, don't require the number.
I get this error:
"reserveVehicle must be a
number
type, but the final value was:NaN
(cast from the valueNaN
)."
This makes sense (kind of) because, well null
is Not a number. But as I'm trying to tell it that it shouldn't be required, in my opinion it shouldn't try to evaluate it.
Did I miss any key concepts of Yup
?
You should use typeError
Here is an example from my code:
amount: Yup.number()
.typeError('Amount must be a number')
.required("Please provide plan cost.")
.min(0, "Too little")
.max(5000, 'Very costly!')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With