Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional field validation based on boolean prop

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.

like image 584
weno Avatar asked Mar 02 '23 23:03

weno


1 Answers

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'),
})
like image 127
NinjaDev Avatar answered Mar 05 '23 17:03

NinjaDev