Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda