weno
weno

Reputation: 856

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.

Upvotes: 5

Views: 2484

Answers (1)

NinjaDev
NinjaDev

Reputation: 402

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'),
})

Upvotes: 8

Related Questions