4
votes

I have a react formik form, where there is a select field, say the field has values A,B,C,D,E,F.

now say, another field , ChooseSubType , only shows up if I choose B or D and this field will only be a required field when it shows up and not before that.

now, how do I make that work?

here's code for the first field i.e. select field

chooseAlphabet: Yup.string().required('field required'),
chooseSubType : Yup.string().when('chooseAlphabet',
('chooseAlphabet',schema)=>{
   console.log('value business : ',chooseAlphabet);
   if(chooseAlphabet === "B"||"D"){
     return schema;
   }else{
     return schema.required('field required');
   }
  }),

but this code isn't working.

now, what changes do I make here to make this work as I want it to?

3
Are you getting validation errors or the chooseSubType isn't showing up?Snekse

3 Answers

6
votes

I know its bit late but you can try this

chooseSubType: yup.string().when('chooseAlphabet', {
  is: 'B',
  then: schema => schema,
  otherwise: yup.string().when('type', {
    is: 'D',
    then: yup.string().required('field required.')
  })
})
3
votes

you can use the same code just a refinement you need to add please check below code.

chooseAlphabet: Yup.string().required('field required'),
chooseSubType : Yup.string().when('chooseAlphabet',
(chooseAlphabet,schema)=>{
    console.log('value business : ',chooseAlphabet);
    if(chooseAlphabet === "B"||"D"){
       return schema;
    }else{
       return schema.required('field required');
    }
}),
2
votes

For you 2nd parameter schema is undefined.

 chooseAlphabet: Yup.string().required('field required'),
        chooseSubType : Yup.string().when('chooseAlphabet',
        (chooseAlphabetValue)=>{
           console.log('value business : ',chooseAlphabetValue);
           if(chooseAlphabetValue=== "B"||"D"){
             return Yup.string();
           }else{
             return Yup.string().required('field required');
           }
          }),