Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
Formik passing context to yup validation

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!