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.
Upgrade

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
Debugging in React Native: Flipper vs React Native Debugger vs Reactotron
Agile Test Management - Zephyr for JIRA
The Difference Between MongoDB and Firestore, and When You Should Use Each

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.

-- 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!")
  .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}>
    <input
      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>

  </form>
  );

};


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


render(<MyEnhancedForm nameMax={10} />,
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.

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.

FullStack Labs Icon

Let's Talk!

We’d love to learn more about your project. Contact us below for a free consultation with our CEO.
Projects start at $50,000.

company name
name
email
phone
Type of project
Reason for contact
How did you hear about us?
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.