DEV Community

Cover image for Handle form better in Nextjs with react-hook-form
Ademola Onasoga
Ademola Onasoga

Posted on

Handle form better in Nextjs with react-hook-form

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

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

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

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

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

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

Full form

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

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

Disable button

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

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

Error message

Full form:

These is just few reason to consider using React-hook-form in your foImage description
rm management toolkit. And I will follow these articles up with other use cases.
React hook form

Oldest comments (8)

Collapse
 
bluebill1049 profile image
Bill

Thank you for writing this detailed blog post. <3

Collapse
 
hellodemola profile image
Ademola Onasoga

Thanks Bill.

Collapse
 
michealadisa profile image
Micheal Adisa

Thank you for documenting this, great step by step article writing approach.

Collapse
 
hellodemola profile image
Ademola Onasoga

Thanks @michealadis

Collapse
 
ajit_a profile image
Ajit Arora

Thank you for this document,it help me @hellodemola

Collapse
 
hellodemola profile image
Ademola Onasoga

I am glad to hear that. Thanks for the feedback.

Collapse
 
f00000b profile image
David A

Thx, you saved my day!

Collapse
 
hellodemola profile image
Ademola Onasoga

Thank you, David, for the kind words.