Creation of React Forms with Formik & Yup together…

Yudhajit Adhikary
5 min readJul 25, 2019

Hi Guys!!! Hope you are doing well. Let’s start our discussion on Formik and Yup with the tagline mentioned below,

Build forms in React,without the tears”- Jared Palmer, Creator of Formik.

So, let’s see what are the reasons of tears behind creating a React form. From my personal experience, when I started working with React, creating, validating react forms, sending data, handling the onSubmit( ) function and onChange( ) function didn’t create much problem for me. But when the form size became larger, creating the states and the input fields with proper onChange( ) and onSubmit( ) functions, adding validation for each input fields in the form, creating a boolean state by making it true or false according to the validation status, all these activities really made the things complicated. In this situation, Formik is proved to be the best solution for all such problems in creating a form. Formik contains a higher order component that helps in managing react states, validation of input fields, error management, form submission etc. with several techniques which actually makes the management of React forms much much easier.

So, let’s explore the concept in a more detailed manner,

Before starting our discussion, i would like to show you the code first,

App.js
App.js

Now, let’s begin the discussion by referring the above code. Here, we have imported Field, Form and ErrorMessage from Formik and the form validation is done with the Yup object schema validator which hooks into Formik via the handy validationSchema prop. This code is an example of Signup form built with <formik/> component. <Fields/> acts as the input field for the <Form/> inside <formik/> tag. <ErrorMessage/> acts as the div which shows error message. Yup is used for validation of the input fields inside form and Formik by default uses Yup for validation via validationSchema prop. InitialValues declares the states that we are gonna use in the form creation and also initializes the value of the states,if the name of the <Fields/> tag and state’s name inside the initialValues are same the values gets automatically changed and updated without calling any onChange( ) function inside the input fields and stores the values as the Javascript object called fields .

The Yup library makes it easy to validate individual values in a JavaScript object. So Yup takes each values by Yup.object.shape( ) methods to validate them individually.So for each fields we have set some criteria inside the form. .email( “Email is invalid”) means the value of the Email field must be of email format if it is not the error message “Email is invalid” will be displayed. Similarly .required means those fields are compulsory otherwise it will throw error with message “Email is required” .Similarly .min(6, “Password must be atleast 6 letter”) means the minimum length of the Password is 6 otherwise it will show error message “Password must be atleast 6 letter”, .matches(/[A-Z]{2}\d{2}[A-Z]{2}\d{4}$/i,”invalid password”) means the first two letter of the password must be alphabets followed by two numbers after that there will be two alphabet and it will end with 4 numbers for example,WB12AR1234 or wb12ar1234 ,we have used regex expression to define the valid pattern of the password where ‘ /i ’ means the pattern is not case sensitive,If the value of the password does not match the defined pattern it will show the error message “invalid password”.

In Signup form, the most common part is confirm Password and A common situation when implementing a Sign Up form is asking the user to input their password twice and then the app can make sure they match. To do this, we need the validation of our ConfirmPassword value to reach outside of itself to make a comparison with the Password value. This can be done with Yup’s ref function. This is done by :

.oneof([Yup.ref(‘password’),null],’Password does not match’) method means we can able to reference the value of password with ref. We use the oneOf function to ensure that ConfirmPassword either matches password or if it is left blank and matches null then it passes the validation for the time being. The second argument to oneOf is a custom validation message when this validation fails.

The most interesting thing about formik is that the error message of each input fields will automatically shown in the <ErrorMessage/> tag provided the name of the <Field/> tag and name of the <ErrorMessage/> tag is same.

Till now, we have created a form designed by Bootstrap 4. Inside the <Form> we have used a bootstrap input field class ‘form-group’ inside which we have placed our <Field/>,<ErrorMessage/> and <Label/>tag for each input fields .Inside <Field/> tag we have used class name={‘form-control’+(errors.field name && touched.field name? ‘is-invalid’:’ ’)}/> means if there is any error inside the input field value the classname of the Field will change from form-control to from-control is-invalid.In Bootstrap ‘form-control’ are the classes which is specially designed for form input fields designing . Similarly, The <ErrorMessage/> tag will appear when ever an error occurs into the input fields of the form and class of the <ErrorMessage/> tag is ‘invalid-feedback’ which is the bootstrap class for showing invalid-feedback or error-message .So Our SignUp form is now ready and onClicking the Register button the onSubmit( ) function inside the form automatically executes by showing the Alert of success message followed by fields JavaScript object which is created by formik on submitting the form and we stringifing them into string , by using JSON.stringify( ) method. Our Form will finally look like this .

Initial design of the form when user have not started filling it up.
Showing error message when user is entering incorrect Pattern and Input.
Showing Success message with the fields value that user has entered on Clicking Register Button.

So, That is all about a little implementation of Formik.

You can find whole code on my GitHub repo

CODE:

I would highly recommend you people to go through the documentation of Formik and Yup. There are more ways to use formik for creating react forms according to the development requirements.

Hope, this article is gonna be really helpful to you to kick off your web development skill to one more step ahead using formik for creating React Forms.

Happy Coding….:)

--

--

Yudhajit Adhikary

Web developer by profession,Photographer,Blog Writer,Singer,Pianist,Seeker of Solution