FullStack Labs

Please Upgrade Your Browser.

Unfortunately, Internet Explorer is an outdated browser and we do not currently support it. To have the best browsing experience, please upgrade to Microsoft Edge, Google Chrome or Safari.
Welcome to FullStack Labs. We use cookies to enable better features on our website. Cookies help us tailor content to your interests and locations and provide many other benefits of the site. For more information, please see our Cookies Policy and Privacy Policy.

How to use Yup context variables in Formik validation

Written by 
Joeseph Rodrigues
Senior Software Engineer
How to use Yup context variables in Formik validation
blog post background
Recent Posts
Getting Started with Single Sign-On
Choosing the Right State Management Tool for Your React Apps
Accessibility in Focus: The Intersection of Screen Readers, Keyboards, and QA Testing

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.

Table of contents

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.


Let's start with the file itself:

// withFormik.js

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

export default ({ validationSchema, validate: _, ...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.


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;
        }, {});


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.

-- CODE language-jsx keep-markup --
/* 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!")
  .when("$nameMax", (max, schema) => (max ? schema.max(max, “too long!”) : schema))

const MyForm = (props) => {
  const {
  } = props;
return (
  <form onsubmit="{handleSubmit}"></form>
    {errors.name && touched.name &&<div id="feedback">{errors.name}</div>}
    <button type="submit">Submit</button>



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

render(<myenhancedform namemax="{10}">, </myenhancedform>

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.

Joeseph Rodrigues
Written by
Joeseph Rodrigues
Joeseph Rodrigues

As a Senior Software Engineer at FullStack Labs I'm focused on building complex mobile applications using React Native. Prior to FullStack Labs I was a Full Stack engineer at Omadi, Inc.

People having a meeting on a glass room.
Join Our Team
We are looking for developers committed to writing the best code and deploying flawless apps in a small team setting.
view careers
Desktop screens shown as slices from a top angle.
Case Studies
It's not only about results, it's also about how we helped our clients get there and achieve their goals.
view case studies
Phone with an app screen on it.
Our Playbook
Our step-by-step process for designing, developing, and maintaining exceptional custom software solutions.
VIEW OUR playbook
FullStack Labs Icon

Let's Talk!

We’d love to learn more about your project.
Engagements start at $75,000.