Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

266
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda