Reputation: 2733
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?
Upvotes: 6
Views: 10404
Reputation: 3870
The first params should be the array. The below code should work. Noted on the first param, I changed it to [chooseAlphabet]
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');
}
}),
Upvotes: 0
Reputation: 53
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');
}
}),
Upvotes: 4
Reputation: 1118
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');
}
}),
Upvotes: 2
Reputation: 391
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.')
})
})
Upvotes: 9