Handle form better in Nextjs with react-hook-form
Tags: nextjs, react, javascript
Published: 2022-06-05 01:08:47

_On a regular tuesday afternoon, you attempted to implement a registration form with 3 field inputs, and for each field you need to have at least 1 validation. The most common approach to handle this would be with an `Onchange` function with a dash of `Regular Expression`. But as the form gets more complex with new set of validations and additional fields, you thought to yourself that there must be a better way to handle this. Alas! You were right all along._

In this article, we look at how to handle simple form data and validation with __React-hook-form__. Our case study is a registration form that collect users' information; first name, last name, email address, phone number and address. 

We will validate each fields with at least one validation. For example, a mobile number field should not accept an email value or any letters for that matter. And this use case also assumes that names are not in numbers ( I know '2 pac' has a number, but let's limit the scope to only letters for name inputs). And if the fields are compulsory, it should not accept an empty value, the field must be filled.


## Handling form using OnChange



![OnChange function form management](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0mjt3quvvcexkfncfdlx.png)
 
 
As shown above, for every new fields introduced, there would be a need to keep adding a new state to handle it. So if we have, 14 fields in the form...you guessed it, 14 states. 

> I know some of you are thinking that this componenet can still be further broken down into container and stateless form, you are right. However, we are using it this way so that it can be easy to follow

### Let's add validation with regEx

Validate that no fields cannot be empty

![validation for empty fields](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3sjxv8c0i63h3nvcr2vk.png)
 
The form will be invalid if any of the fields are empty.

Now let's go a step futher by preventing the form from fulfilling if the value entered for first name or last name is a number or even has space in between the words. For that we will use a regular expression, also known as regEx. RegEx are patterns used to match character combination in strings. [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions]

We will define a regular expression for that validation:
![RegEx validation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f417k8iiunum0l9w9ek0.png)
 
We have added two validations for names, and we might need more; like the names should be at least three characters. And we have four other fields to validate deeper. This is looking like a lot of work. And what if, the form is longer and we are actually calling an API to submit the form, do we want the user to fill all the form before she realises all the checks. That would be frustration for the user.  

## React-hook-form to the rescue

Add React-hook-form in the follow steps:

1.  `npm install react-hook-form` or `yarn add react-hook-form` if you use yarn.
2. Add `import { useForm } from 'react-hook-form'` to your file
3. Add `const { handleSubmit, register } = useForm({mode: 'onChange')}` to your component.
![use form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ibx37jkcs3nzzc7lomrb.png)
 
The handleSubmit works to submit the form, and the register works like the onChange. The mode, 'OnChange' means you want to form to be reactive in real time.

![use form react-hook-form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/clemlkg9wzlv60f7dyx9.png)
 
 
Just like that, you trim off all the useState and extra onChange collection away. 

Can we handle some layer of validations using this package, of course.

![useForm](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4f5531w9bk0ik2aarz9.png)
 
![Full form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7oiv5zjatgz67ljrv8zi.png)
 
Just pass your RegEx inside the pattern object in the register, the user is prevented from submitting her form if the fields are empty or the wrong patterns are entered. 

Of couse, there are other form of validations to add to the form fileds and the form itself, eg preventing the form from been clickable.

For that we will add a new object in the `useForm` function, formState.

![FormState](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t2lcq7mcspthblcpswm4.png)

And we will add a disabled option to the button to disable the button unless all the fields are valid

![Disable button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0xiyihhvo8x1e1zkple5.png)

__Finally__ , we want to give the user a feedback in realtime of why the button is still disabled even when all fields are entered, it might be that the patterns entered are wrong. eg. '2 pac'. For that, we will need to add another item in the formState, `errors`.

![Adding errors](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jvt0t9f3y1evko8z7r5e.png)

Then add the feedback error message in the body of the form

![Error message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e8o70lxs6b935c51kppu.png)

Full form:

 

These is just few reason to consider using `React-hook-form` in your fo![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1bvx4b73iumlr957121k.png)
 rm management toolkit. And I will follow these articles up with other use cases.
![React hook form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o129kjowuqc6dvlms8te.png)