Reputation: 21
I'm trying to make a field in a form required if my array contains a certain string.
For example, the field 'spouseName' should be required if the array familyMembers contains 'spouse'. Is it possible to use the .when() function to check the values in array? I'm using it to check the value of strings in other parts of the forms like this:
jobTitle: Yup.string().when("jobStatus", {
is: "employed",
then: Yup.string().required(requiredError)
})
is there a way to do something like:
spouseName: Yup.string().when("familyMembers", {
contains: "spouse",
then: Yup.string().required(requiredError)
})
Upvotes: 2
Views: 5189
Reputation: 31683
Instead of passing the second parameter as a object, you could pass it as a function that receives the value of the field from the first parameter (in your case, the value of familyMembers) and the schema to be modified (in your case, add required).
You can see how to do this in the docs mixed.when (It's the last example).
e.g. from the docs
yup.object({
isBig: yup.boolean(),
count: yup.number().when('isBig', (isBig, schema) => {
return isBig ? schema.min(5) : schema.min(0);
}),
});
So in your case, it should be something like
spouseName: Yup.string().when("familyMembers", (familyMembers, schema) => {
// if it includes 'spouse'
return familyMembers.includes('spouse') ?
Yup.string().required(requiredError) : // add required validation
schema; // don't change anything
}),
})
You can do other logic inside the function and also return diferent schema types.
Upvotes: 2