loading...

Yup, Formik, React: Differing Drop-downs

bowlendev profile image Ryan Bowlen ・1 min read

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.'),
})

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 by:

bowlendev profile

Ryan Bowlen

@bowlendev

React / Java Developer who loves reading, working with youth, robotics, and making cool things.

Discussion

pic
Editor guide
 

Thanks for the post, bowlen.

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

 

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

 

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