DEV Community

Cover image for Yup: The efficient validation schema handler
Adekogbe Florish
Adekogbe Florish

Posted on • Updated on

Yup: The efficient validation schema handler

Understanding how form validation is handled and how to build a schema for it is critical as a Frontend Developer. Forms help users to interact with the system by sending their data to said system for various purposes like authentication, job applications, event registrations and so many more. It is crucial for developers to understand what kind of data should be accepted by different input fields which users will be interacting with and how they can be built.

In this article, we will learn what Yup is all about and how it makes UI development faster and more efficient.

What is Yup?

Yup is a schema builder for runtime data parsing and validation. It defines the rules for validating the data in your form. Different fields have different specifications on what kind of data to accept and instead of manually specifying these by creating multiple functions, Yup is there to make things easier. With this object schema, input values can be verified, parsed and tested based on some configurations.

Why use Yup?

When building a web or mobile application as a developer, concise and efficient coding should be one of the most important things to consider. Fewer and easily readable lines of code with the same result is always better than a lengthier one. Yup promises all of these and more. We get to write schemas for input fields without having to create custom functions by simply using the methods already existing in the Yup library.

How to use Yup

Firstly we need to install Yup, and we can do this with npm or yarn by typing the commands below

$ npm i yup
Enter fullscreen mode Exit fullscreen mode

Installing Yup with npm

or

$ yarn add yup
Enter fullscreen mode Exit fullscreen mode

Installing Yup with yarn

After installation, we would need to add these import statements to the top of the React component we want to use yup in like so...

import * as yup from "yup";`
import { yupResolver } from "@hookform/resolvers/yup";
Enter fullscreen mode Exit fullscreen mode

Introduction to React-Hook-Form

To implement yup effectively, it would be best to use it in conjunction with React-hook-form. Stay with me as I show you how to do that. A brief explanation on React-hook-form is that it is a library with zero dependencies that helps developers manage complex forms with minimal logic implementation. It has inbuilt methods that handles multiple actions and states, importantly the error state.

How to use React-Hook-Form

Firstly we need to install react-hook-form, and we can do this with npm or yarn by typing the commands below

$ npm i react-hook-form
Enter fullscreen mode Exit fullscreen mode

Installing React Hook Form with npm

or

$ yarn add react-hook-form
Enter fullscreen mode Exit fullscreen mode

Installing React Hook Form with yarn

Implementing Schema

Considering development with Typescript, an interface for the type of the input field variables would need to be created and initialized with default values. Here is an example below;

Interface for Form type

Here we have an interface that sets the type of the email and password fields to be a string in both cases. We then assign default values to those fields and in this case, since they are strings the default value for each field will be an empty string as shown. If any of the fields in another instance has a type of number or an array, the default value will be 0 or an empty array respectively.

In any other case and after said type creation, the schema variable would be created with Yup by using the .object method to create an object of the key value pairs with the key as the input variable type like 'email' or 'password' and the value as the specified schema for the input by using methods like .required .string .email. Here is an example below;

Example of Yup Login Schema

Here we have a user login schema that determines the kind of characters that should be accepted by an email field and a password field. .required implies that the field is required to not be empty for the form to be submitted. .string implies that the field must contain only strings. .email implies that the field must be in email format to contain an '@' symbol and a domain at the end.

In summary this schema specifies that the email must accept a valid email, must accept only string characters and must be required for the form to be submitted. It also specifies that the password must accept only string characters and must be required for the form to be submitted. The entire form is also required to be filled before the form can be submitted.

Form with UseForm

The next thing we will need to do is to initialize the useForm hook with the parameters we need like register, handleSubmit and formState for states like errors and isDirty. We will be initializing these parameters to the yupResolver that takes the schema from our Yup schema created previously. Optionally, we can assign default values to the fields with the defaultValues method that can be initialized with an object that contains plausible default values for each of the fields.

Initializing and implementing React hook form

Here, using Typescript LoginModalPropsis the interface for the login component while LoginDatais the interface for the default values of the input fields. Using the defaultVauesmethod, we are basically ensuring that the input fields have the default values of the content of the variable initialValues.

Handling Inputs and Errors

Here we are going to talk about the familiar part of creating the input tag and then unfamiliar part of assigning the hook form values to the input field with in-built props. The method we need to be concerned about is the Register and it is responsible for monitoring what happens when the value changes and saving or registering it as the name implies by accessing the onChange parameter of an input tag.
Now we also need to ensure that we are correctly monitoring what happens when incorrect characters are typed into various input fields. Based on the already initialized schemas, if anything other than a string is typed into the password field, an error state is triggered. With Yup, all we need to do is access the error message particular to a specified input field and then display it. Here is an example below;

Input tag implementing react-hook-form

Submitting the form

Finally we are done with our form implementation and all we need to do is submit the form. To do this, we just need to create a function with a type of SubmitHandler which is a parameter imported from react-hook-form while passing the interface we created LoginData into it to specify the type. Here is an example below;

Submit function for Yup React hook form

The next step is to create a submit button that will have a regular onClick property where we will pass a method from react-hook-form's useForm variable called handleSubmit (You can check the snippet above for the initialization of handleSubmit).In this handleSubmitmethod, we will pass the earlier created onSubmit function into it as a parameter. Here is an example below;

Submit button for react-hook-form

Conclusion

In this article, you learned about YUP schema validator, including the React-hook-form, and the Register method which are some of the most important libraries for form validation and submission. You must optimize your form schemas to ensure the efficiency and readability of your code base.

Properly using YUP schema to validate your input fields in your different forms reduces your redundancy and increases your efficiency by making it easier to write validations for enormous forms as the case may be. It also makes your submission more optimized. However, there are other mechanisms that can be used to handle form validation like Formik but Yup is more effective. Whether you’re a beginner or an expert, this form validation schema libraries can help you achieve your web developing goals faster. Start implementing YUP in your projects today to explore and enjoy from its various benefits.

Top comments (0)