I've searched the internet literally everywhere, and also the docs but I couldn't find a solution that works in my current project. Quick bit of context:
We have a form, which displays additional fields depending on whether you're adding or editing. When adding, we have 2 different fields. When editing, we have 5 different fields.
Now when we are adding, I do not want these remaining three fields to be validated. Because they will be required when you edit your form. This is where the context will come in.
Currently I'm using the validate prop on the <Formik /> component like so:
<Formik
{...}
validate={(values: FormValues) => {
try {
validateYupSchema(values, getVersionsSchema, true, {
mode: "testing"
});
} catch (e) {
return yupToFormErrors(e);
}
return {};
}}
>
The validateYupSchema function accepts these 4 parameters which I've filled in:
values: T, schema: any, sync?: boolean, context?: any
Now in my validationSchema, I'd like to access this context object. Currently googling for the past 6 hours it constantly recommends me this approach:
export const getVersionsSchema = (t: TFunction<Namespace<"en">>) =>
Yup.object().shape({
{...}
optIn: Yup.string().when("mode", (mode, schema) => {
console.log(mode, schema);
return schema.required("test");
}),
{...}
});
So here you see I'm using when and apparently I have to pass the variable as a string name as the first argument, and a function as the second argument with the context variable name and the schema as arguments.
However, when I log mode in this case, it's undefined...
Can anybody point me in the right direction perhaps?
Here's a codesandbox:
https://codesandbox.io/s/condescending-water-3fmvsv?file=/src/App.js