React Hook Form Show Validation Error Messages Tutorial

In this step by step tutorial, we will reveal how to show custom error messages in React application. To build the form, we will use the React Hook Form and Yup libraries.

From the user experience’s standpoint, it is imperative to show informational messages when validation checks fail.

This feature helps your site visitors to take relevant action regarding the appropriate input field values.

A validation error message generally enables you to set a custom error message that we display to the user, especially when the specific validation checks fail.

This article will use the Yup and React hook form packages to build the basic form with a few input field values.

We will just take the mild approach to define and expose the validation error messages with the Yup schema associated with React Hook Form.

How to Display Validation Error Messages with React Hook Form

  • Step 1: Build New React App
  • Step 2: Install Yup Library
  • Step 2: Install React Hook Form Package
  • Step 3: Build Form Component
  • Step 4: Import Form Component
  • Step 5: Run App in Browser

Build New React App

We will start our first step by building a new react project, If you already know the process then jump on to the next step.

Head over to the command line tool of your code editor and execute the command to start the app installation process.

npx create-react-app react-blog

Next, move into your app folder.

cd react-blog

Install Yup Library

We believe you have entered inside your app; from there, you have to invoke the command and let the Yup package settle inside your app.

npm install @hookform/resolvers

Install React Hook Form Package

React Hook Form package will be added to react app; this library offers boundless, performant, flexible, and extensible options to handle forms with easy input validation.

npm install yup

Build Form Component

At this point, the required packages have been added to app. Subsequently, create the new HookForm.js file inside the component/ directory.

You have to import useForm (React Hook Form), yupResolver, and yup; these modules will help you handle the error messages generated after form input validation fails.

Ultimately, add code in HookForm.js file.

import React from 'react'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import * as Yup from 'yup'

export default function HookForm() {
  const formSchema = Yup.object().shape({
    name: Yup.string()
      .required('Name is required')
      .min(3, 'Name length should be at least 3 characters'),
    email: Yup.string().required('Email is required').email(),
  })

  const validationOpt = { resolver: yupResolver(formSchema) }

  const { register, handleSubmit, reset, formState } = useForm(validationOpt)

  const { errors } = formState

  function onFormSubmit(data) {
    console.log(JSON.stringify(data, null, 4))
    return false
  }

  return (
    <div>
      <h2>React Hook Form - Set Validation Error Messages</h2>

      <form onSubmit={handleSubmit(onFormSubmit)}>
        <div className="form-group">
          <label>
            <strong>Name</strong>
          </label>
          <input
            name="name"
            type="text"
            {...register('name')}
            className={`form-control ${errors.name ? 'is-invalid' : ''}`}
          />
          <div className="invalid-feedback">{errors.name?.message}</div>
        </div>

        <div className="form-group">
          <label>
            <strong>Email</strong>
          </label>
          <input
            name="email"
            type="text"
            {...register('email')}
            className={`form-control ${errors.email ? 'is-invalid' : ''}`}
          />
          <div className="invalid-feedback">{errors.email?.message}</div>
        </div>
        <div className="d-grid">
          <button type="submit" className="btn btn-danger mt-3">
            Submit
          </button>
        </div>
      </form>
    </div>
  )
}

Import Form Component

It is necessary to add the form component, ensure that you are in the App.js.

Go ahead and import the Form component within the file main app component as suggested below.

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css';
import HookForm from './components/HookForm'

export default function App() {
  return (
    <div className="container mt-3">
      <HookForm />
    </div>
  )
}

Run App in Browser

If you want to see the form in action, then you have to start the application.

Consequently, it requires a given command to be typed on the command line.

Don’t forget to execute the command to view the app in the browser.

npm start

React Hook Form Show Validation Error Messages Tutorial

Summary

Through this post, we understood how to set validation rules for name and email fields in conjunction with the yup and react hook form.

Our primary purpose was to set and show the validation errors for respective input fields in React.