Yup, Formik, React: Differing Drop-downs
Ryan Bowlen
Posted on June 14, 2019
This assumes familiarity with Formik, Yup, and React.
Today I learned something cool with Yup. Say that you have two drop-downs or fields and you want to make sure that they are different. There’s a really neat way to do this with Yup and Formik.
Let’s go with something easy:
First Flavor: Vanilla
Second Flavor: Chocolate
The user is able to pick through a list of flavors and select their favorites in order. We want these to be different. So in our code we might have something like this:
validationSchema: Yup.object({
vanilla: Yup.string()
.notOneOf([Yup.ref('chocolate'), null],
'Flavors must not match.'),
chocolate: Yup.string()
.notOneOf([Yup.ref('vanilla'), null],
'Flavors must not match.'),
})
Essentially what is happening here is that Formik and Yup are making sure that before your data is captured, that both fields are not the same value. The ‘noOneOf’ method is checking to make sure that vanilla is not chocolate and vice-versa. The ‘Yup.ref’ is grabbing the value of the other drop-down so that you can pass it to the ‘notOneOf’.
Cheers!
Posted on June 14, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.