Back
Integrating Formik & Yup for React Form Validation
In this article, we’ll examine React form validation using the Formik and Yup packages. These libraries make it much easier to deal with forms in React!
In software development, forms offer a way of receiving data from users before sending information to the server. The data obtained through these forms must be validated and checked for mistakes that might break the server or cause problems. For example, you might need to verify that a username contains the required characters, or that the password
field value and confirm-password
field value match. In this article, we’ll examine how form validation in React Applications using two React form libraries: the Formik and Yup packages. To easily follow this article, fundamental knowledge of React is required. The code for the sample project we’ll be working with in this GitHub repository.
What Are Formik and Yup?
Formik is a React/React Native package used for handling forms; it keeps track of form values, errors, and events, and handles form submissions. Formik eliminates the work involved in setting up a state for form fields, allowing you to focus more on other aspects of development.
Yup is a JavaScript schema builder for validating or parsing values. It allows you to model complex or inter-dependent validations using built-in validators or custom validations using regular expressions.
Yup Schema
The Yup schema allows you to create validation schema/rules that values should follow. You can create a Yup validation schema by calling Yup.object().shape()
. You’ll pass the schema object as a parameter with the schema rules as the value for the field keys. The schema has different datatypes: string, numbers, date, tuple, arrays, objects, booleans, and mixed. The mixed method allows you to create a schema that matches all data types or the ones you configured. Next, you’ll learn about the different Yup validation in React methods you can apply to schema types.
Formik allows easy integration with Yup for validating form values and ensures that the submitted data is error-free and matches a predetermined schema. The following sections will cover how to use Formik and Yup to validate forms in a simple React Application.
Create a React App
To create a React app, you’ll need to have Node.js installed. In your terminal, run the following command:
Once you create the application, update the App.css
file with the following styles:
Using Formik and Yup Form Validation
The App.js
file has a simple sign-up form controlled by Formik. In order to validate Forms in React, inject the Yup form validation schema into the Formik object:
In the code block above, we can see the Yup and Formik validation schema for the sign-up form on line 10. This creates a set of rules that each form field will follow.
On line 27, we have the useFormik
hook with the initial values for the form state, the validation schema created with Yup and the onSubmit
event for the form. Next, we linked the Formik values to the input fields. Using the First Name form field as a reference, we connected the field value from Formik to the value attribute and for the input to create a controlled component. Finally, we passed the handleSubmit
function from Formik to the onSubmit
event for the form.
Validation Messages
Validation messages are tips that help the user understand which characters are valid for a specific form field, making them incredibly useful in React form validation. In addition, they serve as a guide for the user in resolving form errors. Validation messages are accessible through Formik errors for each field. We can see this example on line 61. The First Name field validation message can be accessed from formik.errors.firstName
.
Built-in Validators
Yup has some built-in validators that we can implement. As seen in the code block above, we used some built-in validators in the validation schema. As discussed in the previous section, there are different datatypes for a Yup Schema. For each data type, there are different validation methods that can be chained to it. An exception is a boolean datatype that can be either true or false.
Custom Validations (RegEx)
We can create our custom validation rules by using the matches()
method for string schema. This accepts a regular expression and the validation message as a value:
The schema rule above will check if a value is a string and verify that the string value is not empty. Next, it will check to make sure that the minimum length for the string characters is eight. Finally, the following three validation rules for the value are customized using a regular expression:
The first expression checks if there is at least one uppercase letter and one lowercase letter in the string.
The second expression checks if the value contains at least one number.
The last expression checks if the value contains at least one special character.
This validation can be applied in real-life scenarios for creating a strong password, as seen in the code sample in the App.js
file:
Validating a Dynamic Form with Formik and Yup
The Formik validation package also comes with built-in components that let us control the form state and events. In this section we’ll examine how to create a dynamic form using Formik form components and Yup. First, we’ll set up a form that allows us to create a list of items:
In the code block above, we have the Yup schema, which is an array type of strings. As we can see from the Yup validation schema, the array values are required; we cannot have an empty string as an array value.
Next, we imported the Formik
component from the Formik package; this wraps the form. Since we’re working with arrays/dynamic form values, we used the FieldArray
component, which helps with array manipulations. On line 32, we have the FieldArray
, which is used to render each form field and button. The render props from the FieldArray
had helper props passed to them. This prop allowed us to mutate the array values, as seen in the "Add New Item" button, where we used the push()
method from the helpers to add new values at the end of the array. Also, the "remove" button calls the remove()
method on click, with the item's index to remove passed as a parameter:
Finally, to test your dynamic form, you can use the code sample in this codesandbox.
Conclusion
Formik and Yup provide a great way to manage form state and validate values in a form before sending data to the server. They provide a lot of flexibility and ease when creating forms. You can also utilize the Formik form components or hooks to handle your forms in a React application.
For additional information on using Formik and Yup, check the official documentation.