jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.91k stars 2.78k forks source link

feat: provide current values as context to yup validation by default #3786

Closed quantizor closed 1 year ago

quantizor commented 1 year ago

Yup by default only allows for cross-field validation within the same field object. This is not that useful in most scenarios because a sufficiently-complex form will have several yup.object() in the schema.

const deepNestedSchema = Yup.object({
  object: Yup.object({
    nestedField: Yup.number().required(),
  }),
  object2: Yup.object({
    // this doesn't work because `object.nestedField` is outside of `object2`
    nestedFieldWithRef: Yup.number().min(0).max(Yup.ref('object.nestedField')),
  }),
});

However, Yup offers something called context which can operate across the entire schema when using a $ prefix:

const deepNestedSchema = Yup.object({
  object: Yup.object({
    nestedField: Yup.number().required(),
  }),
  object2: Yup.object({
    // this works because of the "context" feature, enabled by $ prefix
    nestedFieldWithRef: Yup.number().min(0).max(Yup.ref('$object.nestedField')),
  }),
});

With this change, you may now validate against any field in the entire schema, regardless of position, when using the $ prefix.

vercel[bot] commented 1 year ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
formik-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 26, 2023 6:10pm
codesandbox-ci[bot] commented 1 year ago

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit aed0b2478d78d66008555dd5cb2ec97dc7d358e5:

Sandbox Source
Formik TypeScript Playground Configuration
jaredpalmer commented 1 year ago

I'm gonna merge the others and release and then merge this and then release a minor