Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

field required based on value of another field - formik, yup

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?

like image 250
faraz Avatar asked Dec 13 '22 14:12

faraz


2 Answers

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.')
  })
})
like image 62
Omkar Gokhale Avatar answered Jan 13 '23 13:01

Omkar Gokhale


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');
    }
}),
like image 21
Gagan Deep Avatar answered Jan 13 '23 12:01

Gagan Deep