Mastering Form Validation with React Hook Form

Mastering Form Validation with React Hook Form

Build Dynamic Forms with Easy Validation and Error Handling Using React Hook Form.

Introduction

Forms, which are used to obtain user information, are an essential aspect of web development. They enable users to input data, like their name, email address, password, and other details, which the server can process and store in a database.

Forms can also be made interactive and dynamic by using JavaScript. Text fields, password fields, radio buttons, checkboxes, drop-down lists, and submit buttons are just a few of the different form elements that can be employed. The user can submit the completed form to the server for processing after filling it out.

A crucial component of web development is form validation, which makes sure that user-provided data is accurate and satisfies the necessary standards. Overall, forms are essential to web development because they let users engage with websites and give a mechanism to gather and store user data.

Form validation

Verifying that information entered into a form meets requirements is known as form validation.

The reason it's a crucial component of web development is that it checks that the information being received is correct, and complete, and serves the form's intended function.

Advantages of form validation include:

Form validation may improve user experience by preventing users from filling in invalid data and seeing error messages by capturing mistakes before they reach the server. A more seamless and user-friendly experience may come from this.

Data integrity is maintained by ensuring that the data being gathered is correct and comprehensive, which is essential for maintaining the integrity of the data being kept.

Security: Form validation assists in preventing security concerns like SQL injection and cross-site scripting assaults by validating and cleaning up user input.

Data Consistency: Form validation helps assure data consistency throughout the application, which is crucial for large-scale systems, by specifying specific standards for the data being entered into a form.

Saving time: By catching mistakes before they reach the server, form validation can save time by reducing the requirement for server-side validation and error handling.

To sum up, form validation is an essential component of web development that enhances user experience, guarantees data security and integrity, and supports data consistency. It is a crucial tool for obtaining precise, thorough, and secure data via forms

React Hook Form

It is a library that offers a quick and straightforward method for creating and managing form inputs. It was designed to make handling form state and validation in React apps smoother. React Hook Form has several important features, including

Simple and user-friendly API.

Performance improvements to reduce re-renders.

Support for components that are both controlled and uncontrolled.

Support for standard and custom validations is built-in.

Default values can be set and the form can be refreshed.

Asynchronous validation is supported.

Any React application, regardless of its complexity or size, can use React Hook Form. Additionally, it works with other well-known libraries, like Redux, React Router and others.

Prerequisites

Note: You should have a basic understanding of React and its concepts, such as components, state, and props.

Official docs

Installation via npm

Installation via Yup,

A simple React form with React Hook Form

The first step, install the library via npm on your terminal.

> npm install react-hook-form

Import the library in your React component.

import { use form } from "react-hook-form";

Use the “useForm” hook in the functional component of the component to launch the form.

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();
  const onSubmit = (data) => console.log(data);

To register the form fields you want to validate, use the register function. If your form has a field called "firstName" and “lastName” for instance, you can register it as follows:

            <input
              type="text"
              name="firstName"
              {...register("firstName", { required: true, minLength: 3 })}
            />
{errors.firstName && (
              <p>Minimum of 3 characters</p>
            )}

<input
              type="text"
              name="lastName"
              {...register("lastName", { required: true, minLength: 3 })}
            />
            {errors.lastName && (
              <p>Minimum of 3 characters</p>
            )}

Register: Form inputs are registered using the “register” function so that the form's state and validation can access them.

Required: If a field is required, the word "required" indicates it. The field cannot be empty when this property is set to true.

With "minLength" and "maxLength," you can specify the minimum and maximum lengths for a string input value. Set the minimum and maximum values for a numerical number with “min” and “max”.

Errors: For each input, the errors object is used to handle validation errors.

The “handleSubmit” function is used to handle the submit event of a form, and it is called with a callback function that will receive the form data when the form is submitted.

<form onSubmit={handleSubmit(onSubmit)}>

</form>

Register a field named “phone”, where we will use “pattern”. The “Pattern” function uses a regular expression to define a pattern for the input value.

          <input
            type="text"
            name="phone"
            {...register("phone", {
              required: true,
              pattern: /^[+][(]{0,1}[0-9]{1,4}[)]{0,1}[-\s./0-9]$/,
            })}
          />
          {
errors.phone && <p className="error">Not a valid Phone Number</p>}

Register another field named “email, where we will be using another “pattern” with the email regular expression.

          <input
            type="text"
            name="email"
            {...register("email", {
              required: true,
              pattern: /^[^\s@]+@[^\s@]+.[^\s@]{2,}$/i,
            })}
          />
          {
errors.email && <p>Not a valid email format</p>}

Another field with the register “password”. This doesn’t have a default pattern like the email field because sites have different password requirements. So we will be using the one that makes the user input a digit, special symbol, uppercase, lowercase, and 8-10 numbers.

            name="password"
            {...register("password", {
              required: true,
              pattern: /^(?!.\s)(?=.[A-Z])(?=.[a-z])(?=.[0-9])
                (?=.[~`!@#$%^&()--+={}[]|\:;"' <>,.?/_₹]).{8,16}$/,
            })}
          />
          {errors.password && (
            <p>
      Password must contain at least a digit, special symbol,
            Uppercase, Lowercase, and 8-10 characters long.
            </p>
          )}

Complete code for the simple form validation.

import { use form } from "react-hook-form";

const App = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <h1> Form Validation with React Hook Form</h1>
        <section>
          <div>
            <label>First Name</label>
            <input
              type="text"
              name="firstName"
              placeholder="Enter your first name"
              {...register("firstName", { required: true, minLength: 3 })}
            />
            {errors.firstName && (
              <p>Minimum of 3 characters</p>
            )}
          </div>

          <div>
            <label>Last Name</label>
            <input
              type="text"
              name="lastName"
              placeholder="Enter your last name"
              {...register("lastName", { required: true, minLength: 3 })}
            />
            {errors.lastName && (
              <p>Minimum of 3 characters</p>
            )}
          </div>
        </section>

        <section>
          <label>Phone Number</label>
          <input
            type="text"
            name="phone"
            placeholder="+234"
            {...register("phone", {
              required: true,
              pattern: /^[+][(]{0,1}[0-9]{1,4}[)]{0,1}[-\s./0-9]$/
            })}
          />
          {
errors.phone && <p>Not a valid Phone Number</p>}
        </section>

        <section>
          <label>Email Address</label>
          <input
            type="text"
            name="email"
            placeholder="
yourname@gmail.com"
            {...register("email", {
              required: true,
              pattern: /^[^\s@]+@[^\s@]+.[^\s@]{2,}$/i,
            })}
          />
          {
errors.email && <p>Not a valid email format</p>}
        </section>

        <section>
          <label>Password</label>
          <input
            type="text"
            name="password"
            placeholder="**"
            {...register("password", {
              required: true,
              pattern: /^(?!.\s)(?=.[A-Z])(?=.[a-z])(?=.[0-9])
                (?=.[~`!@#$%^&()--+={}[]|\:;"' <>,.?/_₹]).{8,16}$/,
            })}
          />
          {errors.password && (
            <p>
              Password must contain at least a digit, special symbol,
              Uppercase, Lowercase, and 8-10 characters long.
            </p>
          )}
        </section>
        <section>
          <button
            type="submit">Send message
          </button>
        </section>
      </form>
    </>
  );
};

export default App;

Pictorial representation of the code in browser view

Image 1: When there is no user input.

Image 2: When a user input complies with the criteria for validation.

Image 3: When a user inputs incorrect information into a field.

Link to live code on CodeSandBox: https://codesandbox.io/s/rough-browser-lkivl1?file

Conclusion

Default React form validation, in comparison, might be more challenging to set up, maintain, handle complex validation situations, and deliver user-friendly error messages. With React Hook Form, you can use advanced capabilities like cross-field validation and real-time validation to validate your forms more effectively and simply for the user.

Therefore, React Hook Form is a perfect option if you want to develop high-quality forms quickly and easily. It offers a versatile and simple way to validate your forms with enhanced functionality and superior speed.