only make a field required when prop passed into component is satisfied

Viewed 21

I have a form that displays a different field based on a prop passed into the form - league. All the examples I have found are based on another value in the form, but not something from outside the form. See the code below.

const LeagueForm = (league) => {

   const validationSchema = Yup.object({
      team: Yup.string().required('Required'),
      players: Yup.object()
      .shape({
        value: Yup.string().required('Required'),
      })
      .when('league', {
        is: league === League.Premier,
        then: Yup.object().shape({
          value: Yup.string().required('Required'),
        }),
      }),
  });


... rest of code in component
}

My goal is to just make the players field required when the league passed in is 'premier'. I have tried many attempts but can't seem to figure it out. See latest attempt below.

Note the reason it is an shape.object is because it is using react-select which shape is like { value: 'foo', label: 'bar' }

1 Answers

Not sure but you can do something like that;

const validationSchema = Yup.object({
      team: Yup.string().required('Required'),
      players: league === League.Premier &&  Yup.object()
      .shape({
        value: Yup.string().required('Required'),
      })
  });

Related