Dynamic validation with Yup and Formik using React hooks

Cristiano Soares
2 min readMar 30, 2020
Fonte: keyholelabs

In this lesson, I will show u how to deal with dynamic validation based on the article: How-to-Create-an-Optional-Dynamic-Validation-Schema-based-on-a-Value-with-the-Yup-Validation-Library and add some features to it.

So, I ran into this issue and became asking myself how to transform a required schema into an optional one using Formik.

Intro

First of all, we’ll create a state that will save our value and with that return if it’s optional or not.

using useState

optionalObject will be our conditional object (it can be an empty one or not) and otherData is where we will send the data of our inputs or what u want to validate.

Optional Schema

Next step is to create a schema for Yup validation and it will look like that:

setting yup’s schema

Here is where the magic happens, using yup.lazy() and passing a value to it, we can switch between a not required schema to a required one, if the value is empty we can say that the field is required so: yup.string().required() if it’s not then: yup.mixed().notRequired(). We can change “mixed” later for string().

Formik

Now, we will set up Formik so we can validate the input field through it:

setting useFormik

I’m using the useFormik hook instead of <Formik>. We set out initialValues with the state we declared before: state.optionalObject.otherData, we pass the optionalRequiredSchema into validationSchema and declare our onSubmit function.

isValidSync

Yup has a function that returns a boolean and we will use that to check if our input field is valid or not:

Our const valid will store this bool so we can use that later.

Linking all together

The HTML structure will look like that:

HTML structure

When the input field is touched and it has some data in it, the error message “this field is required” disappears.

But when using Formik, we have to change the field value and change the state too so Yup can validate it:

using handleChange to set field value

Now that all settings are done, this should do the trick to switch between a required and not required schema.

DEMO

--

--