Home / Articles / Blog

Forms and Validation in React
React Hook FormReact HooksnpmFrontendReactjs

Forms and Validation in React

Introduction to React Hook Form.

FrontendShrey Vijayvargiya

Section 1

Creating a form for your application with proper validation is imperative to accord a pleasing user experience.

But it's never a cakewalk to develop a form with proper validation but we have a decent third-party library for React to develop a form.

So this blog is an attempt to create a form using a React Hook Form.

Getting Started

I will be using the sample Next.JS repository and third-party styling library Tailwind CSS. The choice is completely yours to prefer whichever library you are comfortable with. Go ahead and install the React Hook Form using the below command.

text
yarn add react-hook-form

In the documentation of React Hook Form, they provide an extended way to create forms using third-party UI components, or custom-made components with proper validations. In the image below, the topics on the left-hand side under the Menu section depict how easy this library makes our work in creating a form in React.

Screenshot of docs for React Hook Form on their Website
Screenshot of docs for React Hook Form on their Website

Section 2

Adding Validations

rules is an object which consists of all the validations you want to add, for example, required, max length, min length pattern or regex etc.

Below is the screenshot of the validations -

Validations screenshot of the React Hook Form website
Validations screenshot of the React Hook Form website

Writing Code

We will create a simple form for the user with the following features-

  • First Name — { required: true ,rules: { minLength: 3, maxLength: 20 }}
  • Last Name — { required: true ,rules: { minLength: 3, maxLength: 20 }}
  • Email — {required: true, rules: Should have proper format}
  • Gender — { required: true }

Section 3

Under the Hood

The React Hook Form provides a useForm Hook that exports handleSubmit, errors, register and other objects and functions. The most important are the first 3 ones. By the virtue of their name -

  • handleSubmit provides the values of all forms only when there are no errors
  • Errors objects contain all the errors of our form element.
  • register helps to set fields to the values of our form and to set validation rules.

I will be creating my own InputField and Select Field in a separate folder to avoid maintainability costs and reuse our code.

Followed by using the InputField and SelectField in one single form on the Home page. After adding all the required fields such as First Name, Last Name, Email and so on, I will take care of proper validation.

GitHub Gist

and My SelectField component —

GitHub Gist

I have created simple input and passed the props which I needed the most, for example, rules are most important to handle errors and as soon as we set rules to prop to our input custom input it automatically passes the validation error to our errors object provided by useForm hook.

GitHub Gist

Section 4

Validations rules

To add rules use can either use ES6 spread operators.

text
<input {…register(“firstName”, {required: true, maxLength: 20})} />

This way you are adding the registering field of firstName to our form submit values and some rules such as field is required and its max length should be 20, you also add min length using min as key and value as pair.

My validation errors on localhost
My validation errors on localhost

I have created another real-time interface with a black background for the user to view the errors precisely. Hence you are done with adding forms using React Hook Form.

Section 5

Collecting Values

It is way easier than expected if you have worked with simple custom-made forms in which you update the single state of React useState to collect the values of all the fields of forms but using React Hook Forms the handleSubmit method captures all the values of form fields in one single function and returns it. In addition, you can only grab values from handleSubmit when all validations are passed and the errors object is empty.

Inside your submit input pass handleSubmit to your onSubmit method. handleSubmit function takes a callback where you can grab all the form values as shown below.

GitHub Gist

In the console, you will get all the field values. If you using a button instead of input then call handleSubmit with the onClick property.

GitHub Gist

Section 6

Conclusion

I have hardly added 70/80 lines of code and my form is ready with proper validation.

This is so simple and easy React Hook Form do provide support with 3rd party library like Material-UI.

Don’t forget to check their documentation for detailed understanding, react-hook-form.com

Demo

Until, next time. Have a good day, People.

Shrey

External Links (10)

Explore topics

More in

Weekly letter

Subscribe to iHateReading

Our once-a-week newsletter on programming, jobs, AI, and building products online.

Our once a week newsletter on Programming, Jobs, AI, and Business