Having trouble nailing down this validation schema as Yup is new to me. Basically what I am looking for here is if hasCategory
is true
then I want at least one of the categories to be selected. Right now my schema shape is:
const validationSchema = Yup.object()
.shape({
hasCategory: Yup.boolean().required('Yes or No must be selected for special ad category'),
cat1: Yup.boolean(),
cat2: Yup.boolean(),
cat3: Yup.boolean(),
cat4: Yup.boolean(),
});
So if hasCategory
is true
then I need one of cat1
, cat2
, cat3
, or cat4
to be true
. If hasCategory
is false then I don’t need any of those categories to be truthy.
Any nudge in the right direction would be much appreciated!
3
Answers
This should do the trick
You can make use of
test()
method provided by Yup to perform conditional validations.Explination
using
test()
allows you to get the value of the scheme and its context is set to the parent object giving you access to the fields. itll return true when it passes and false if it fails. theres also ifhasCategory
is true it checks if the others are true as well. and if its false then it just passes automatically.Use an array named catArray instead of multiple property cat1, cat2, ….
I hope this way is useful.