Form Validation with Next.js/React, Part 1
Learn how to validate forms with a “react hook form”

Hello friends! This article explores how to validate forms with a React hook form. If you’d prefer a video tutorial then you can find it here. The starting point for this tutorial can be accessed here, and the complete code found here.
Let’s Get Started!
To validate a form we need to have some basic form as an example. Here it is:
An important thing to note here is that every input element should have a “name” attribute. Thanks to the “name”, data can be correctly assigned to the form object as you will see later.
Let’s move on,
Now we need to install a package for form validation called “react hook form”
In your terminals run:
npm install --save react-hook-form
In the following snippet please follow comments in the code:
Please apply register to every input’s ref in your form. It’s very important to also provide an onSubmit event to the form. To onSubmit you will pass handleSubmit with a callback function to get data from the form.
So far so good, now we are able to get data from the form. To validate inputs we need to provide built-in validators to register function.
Available built-in validators are:
- required
- min
- max
- minLength
- maxLength
- pattern
- validate
You can also create your own validator but about this later. Now let’s apply validators to the title and city input:
The important part here is to register a built-in validator. To display an error message you need to check for a specific error located in the error object under the key of input “name”, e.g: errors.title on the input of title.
To check for a specific error you need to check for an error type:
errors.title?.type==="required"
Whereas type is the key under which you registered validator on the input:
ref={register({required: true, maxLength: 30})}
Now let’s talk about custom validators. It’s actually very simple to create one. A validator is just a function that takes a value from the input and returns true or false. When false is returned, the error is set on the error object. When true is returned then the error is removed, which ultimately means that the input is valid.
Let’s create a simple validator that verifies that the input value is starting with an uppercase letter:
Register the validator on input:
ref={register({required: true, maxLength: 30, validate: { firstLetterUpper }})}
Now we are able to check for this error type:
{ errors.title?.type === "firstLetterUpper" && <p>First letter should be uppercased!</p> }
Conclusion
All done! This is how you can implement a simple validation with a React hook form. In the second article on form validation you will learn how to validate more complicated components; for example, “date pickers”.
Finally, you can find more of my courses here.
Best, Filip