DEV Community

Ryan Bowlen
Ryan Bowlen

Posted on

Yup, Formik, React: Differing Drop-downs

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.

ice cream cones

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.'),
})
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (3)

Collapse
 
dance2die profile image
Sung M. Kim

Thanks for the post, bowlen.

Would you add the syntax highlighting for the code snippet?
Please refer to this Markdown Cheatsheet 🙂

Collapse
 
bowlendev profile image
Ryan Bowlen

Thanks for the reference! It's fixed now and looks so much cleaner.

Collapse
 
dance2die profile image
Sung M. Kim

You're welcome and thank you for taking your time to update the post~