Designing a React Form with Validation: The Easy Way

Tom Bonanni
2 min readMar 3, 2020

The title says it all. You’re just here for the code anyway. You know the drill.

npm i yup formik

Yup and Formik are my two libraries of choice for building forms in React. Yup is a fantastic schema building tool and Formik works nicely in conjunction.

First: Building the Schema

It’s not necessary to build the schema first but I like to do it that way. Let’s say that we have some business requirements for this form. The quantity must be a positive integer, the color must be one of red blue or yellow, the date_needed must be a valid date, and lastly, all of the fields are required before submission. Seems like a lot, huh? It’s not. Here’s the code:

Clean, simple, and readable.

Second: Building the Form

The beauty of using Formik is that the most common form elements (like error messages and fields) are abstracted out for you, so you only have to focus on writing the basic structure of the form.

Let’s say that our validation requirements require us to show specific error messages. For example, if a non-integer is entered for the quantity our error would say “Quantity can only be a whole number”; but if they enter a negative whole number, that same error message would show "Quantity can only be a positive number”. This can be accomplished by modifying our FormSchema. I will do that as well as create the Formik form. Here’s the code:

This code will generate a form with all of our needed fields, it will validate them in real time as a user enters information, and it will display the custom error messages to the user under the respective form field. Wow. That’s an enormous amount of functionality in <50 lines of code.

Note: The onSubmit method is passed to this form as props for the sake of separating concerns. The onSubmit function will automatically be passed the form values as an argument when the form has successfully passed validation and has been submitted.

Conclusion

In <50 lines of code we have created a reusable form in React with real-time validation logic and custom error messages.

--

--