Form Validation using Formik & Yup in React.js

Muhammad Zain Tariq
3 min readDec 16, 2020

--

A Tutorial to Validate a Form using Formik and Yup in React.js.

In this Blog, You will Learn

  • What is Formik?
  • What is Yup?
  • Form Validation using Formik and Yup.

What is Formik ?

Formik is the world’s most popular open source form library for React and React Native. Formik comes with battle-tested solutions for input validation, formatting, masking, arrays, and error handling. This means you spend less time writing form code and more time building your next big thing.

Formik is a small library that helps you with the 3 most annoying parts:

  1. Getting values in and out of form state
  2. Validation and error messages
  3. Handling form submission

Further its size as campared to Redux-Form is less because Redux-Form is 22.5 kB minified gzipped whereas Formik is 12.7 kB

What is Yup ?

Yup is a 3rd party library for validators .Yup has an API that’s pretty similar to Joi / React PropTypes but is small enough for the browser and fast enough for runtime usage.

Formik has a special config option / prop for Yup called validationSchema which will automatically transform Yup's validation errors into a pretty object whose keys match values and touched.

Form Validation using Formik and Yup

Now we will create a React.js app for form validation using formik and yup in following steps.

Step1.

First of All we will create a React.js project using following command with your project name in my case it is formik-form.

create-react-app formik-form

Step2.

Now move into your project root directory using terminal and now install Formik in your project using following command

npm install formik --save

Step3.

After installing Formik we will install yup so write following command in your terminal

npm install yup --save

Step4.

Now you can see in below picture in which you can saw my src folder their will only 3 files index.js, App.js and App.css

index.js file is the root file where as App.js file have all of my form validation with formik and yup code and App.css is for styling purpose .

Code for index.js is below

and code for App.js is Below in this code first we import all necessary files and resources from line 19 to 38 we are writing Yup code and when we submit all data correctly their will be a delay of 0.5 second and a alert will display our information

and App.css code is given below

Final Look for the From will be as shown in figure below

Conclusion

You learn how to create form validation using formik and yup in react.js

if you like this blog follow me for more blogs like this topics and you can connect with me on Linkedin

--

--

Muhammad Zain Tariq
Muhammad Zain Tariq

Written by Muhammad Zain Tariq

Full Stack developer |MERN | Software Engineer

No responses yet