I'm still a newbie to React and Yup. I've got a form that has a multiselect dropdown (bookTypeStrings), and a field will conditionally appear if "Other" is selected from the dropdown. This Other textbox should be required if "Other" is selected. However, my conditional validation of adding the field as required when conditions are met isn't working correctly. When I empty out the Other textbox and tab/focus out, and the "Other" option is still selected in the dropdown, it is not showing it as required.
const validationSchema = yup.object({
...
otherBookType: yup
.string()
.max(50, 'Must be 50 chars or less')
.when('bookTypeStrings', (bookTypeStrings, schema) => {
console.log('in conditional check');
console.log('bookTypeStrings: ' + bookTypeStrings);
if (bookTypeStrings.includes('Other')) {
console.log('Other is selected');
return schema.required('Required if Other is selected');
} else {
console.log('Other is not selected');
return schema;
}
})
});
...
function BookDetailPage() {
const [otherBookType, setOtherBookType] = useState<string>('');
const [bookTypeStrings, setBookTypeStrings] = React.useState<string[]>([]);
}
I'm not sure what I'm doing wrong exactly, but when I run this and look at the console logging, my output is the following:
in conditional check
bookTypeStrings: A,B,Other
Other is not selected
Any idea as to why it's not hitting the if condition instead of the else condition?
Please try this, as given in the documentation
let schema = object({
isBig: boolean(),
otherBookType: Yup.string()
.when('bookTypeStrings', {
is: (val) => val.includes("Other")
then: () => Yup.string().required(),
otherwise: () => Yup.string(),
})
});
This will make the field otherBookType
required when the value of bookTypeStrings
is "Other".
Hope this helps.