Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup.when: "`NaN` (cast from the value `NaN`)"

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 value NaN)."

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?

like image 815
sandrooco Avatar asked Nov 08 '19 16:11

sandrooco


1 Answers

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!')
like image 66
Gaurav Avatar answered Sep 30 '22 02:09

Gaurav