How to use Yup context variables in Formik validation

Written by
Last updated on:
October 1, 2025
Written by
Last updated on:
October 1, 2025

The validation library Yup allows you to pass in values, which aren’t validated themselves, to aid in validation using a context. This is useful for making sure a reference to another object is valid, by passing in an instance of the other object.

In vanilla Yup, this is easy, but the Formik integration with Yup excludes this feature. In this article, we’re going to write a custom `withFormik` higher-order component that will allow you to use any passed prop as context in your validation.

Setup

Let's start with the file itself:

// withFormik.js

import { withFormik } from "formik";
import set from "lodash/set";

export default ({ validationSchema, validate: _, ...options }) =>
 withFormik({
   ...options,
   validate: (values, props) => {
     try {
       validationSchema.validateSync(values, {
         abortEarly: false,
         context: props
       });
     } catch (error) {
       if (error.name !== "ValidationError") {
         throw error;
       }

       return error.inner.reduce((errors, currentError) => {
         errors = set(errors, currentError.path, currentError.message);
         return errors;
       }, {});
     }

     return {};
   }
 });

Formik natively supports Yup validation objects, which are passed in as validationSchema, or you can opt-out of the Yup integration and pass in a custom callback via validate. This method relies on basically snubbing the 3rd party validation method and commandeering the validate callback internally. We’ve found that mixing and matching Yup with custom validation functions isn’t very manageable, so we’re not losing much by cutting out validate. Going through the custom HOC, we can see that we’re basically wrapping the withFormik function, passing along most arguments (aside from the two validation params) and defining our own validation callback.

Breakdown

This section is where the rubber meets the road. Passing in values and props, you will now be able to access props by their name using Yups context format, which we find quite valuable when using the when validation.

validationSchema.validateSync(values, {
          abortEarly: false,
          context: props,
        });

This section parses the payload of errors from Yup validation, massages them into a structure that Formik will parse, and applies them to the correct field. If you set abortEarly to true in your implementation, you will need to build your own parsing mechanism.

return error.inner.reduce((errors, currentError) => {
          errors = set(errors, currentError.path, currentError.message);
          return errors;
        }, {});

Conclusion

Since our custom withFormik function modifies so little of the original withFormik definition, we should be able to adhoc replace any original usage, as long as we are not using the custom validate option. In the example below, I only changed the import path, added a piece of validation that uses context, and added the relevant prop to MyEnhancedForm.

/* app.js */
import React from "react";
import { render } from "react-dom";
import * as Yup from "yup";
import withFormik from "./withFormik";

const validationSchema = Yup.object().shape({
  name: Yup.string()
  .min(2, "Too short!")
  .required("Required")
  .when("$nameMax", (max, schema) => (max ? schema.max(max, “too long!”) : schema))});

const MyForm = (props) => {
  const {
    values,
    touched,
    errors,
    handleChange,
    handleBlur,
    handleSubmit
  } = props;return (
  <form onsubmit="{handleSubmit}"></form>
    
      type="text"
      onChange={handleChange}
      onBlur={handleBlur}
      value={values.name}
      name="name"
  />
    {errors.name && touched.name &&<div id="feedback">{errors.name}</div>}
    <button type="submit">Submit</button>
  
  );
};

const MyEnhancedForm = withFormik({
  validationSchema,  mapPropsToValues: () => ({ name: "bob" }),  handleSubmit: (values, { setSubmitting }) => {  alert(JSON.stringify(values, null, 2));  setSubmitting(false);
  },})(MyForm);

render(<myenhancedform namemax="{10}">, </myenhancedform>
document.getElementById("root"));

Leveraging techniques like the above, we have had the opportunity to address our clients’ concerns and they love it! If you are interested in joining our team, please visit our Careers page.

Frequently Asked Questions

Formik does not natively support passing context variables into Yup validations, but you can work around this by creating a custom wrapper around Formik. This wrapper allows you to inject props as context into your validation schema. By doing so, you can write more dynamic validation rules that reference external values, such as limits or related fields, while keeping your form setup clean and consistent.

Formik integrates closely with Yup, but it doesn't automatically allow context values to be passed during validation. By writing a custom wrapper, you intercept Formik's validate function and attach your own context properties. This approach ensures your Yup schema has access to additional props, making it possible to handle more advanced scenarios like conditional validations, cross-field checks, and dynamic limits.

Context variables let you build smarter, more flexible validation rules. For example, if you need to validate a field based on a maximum value that changes depending on user input or a prop, you can pass that value into your Yup schema via context. This way, your schema stays reusable and avoids hardcoding logic directly into the form component.

When Yup runs your validation, it may return multiple errors at once. The custom wrapper parses those errors and maps them to the correct fields so Formik can display them properly. By enabling error mapping, you maintain Formik's default error-handling behavior while still taking advantage of dynamic context-driven rules.

Yes. Because the custom wrapper modifies only how validation is handled, you can replace your current Formik implementation without rewriting your forms. Your existing fields, handlers, and submission logic will continue working the same way — the only difference is that you gain the ability to pass in and use context variables within Yup.