I want the favoriteAlcohol
field to be validated/required only if props.isAdult
passed to the component is true
.
Yup.object().shape({
favoriteAlcohol: Yup.string().when(props.isAdult, {
is: true,
then: Yup.string().required(),
}),
name: Yup.string().required('Nazwa jest wymagana'),
})
How can I do that?
Above solution does not work, because when
takes form's "keys" as a first argument, and I passed prop.
One working solution would be to map prop.isAdult
to isAdult
form value field, and then I could pass 'isAdult'
as a first argument to the when()
function. Not the best solution, though.
const favoriteAlcohol = props.isAdult ? {favoriteAlcohol: Yup.string().required()} : {}
Yup.object().shape({
...favoriteAlcohol,
name: Yup.string().required('Nazwa jest wymagana'),
})
If props.isAdult = true then, it will make
Yup.object().shape({
favoriteAlcohol: Yup.string().required(),
name: Yup.string().required('Nazwa jest wymagana'),
})
Otherwise, it will make
Yup.object().shape({
name: Yup.string().required('Nazwa jest wymagana'),
})
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