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.