React 18 Display Validation Error Messages with Hook Form Tutorial

Last Updated on by in React JS

As a React developer, you must know how to implement validation in form, and a form may hold one or more than one input element.

If you want to get the user-provided data in a subtle manner, then you must show reverence to proper error handling.

In this tutorial, we would like to show you how to add validation in React, show appropriate error messages in React application using Hook Form and Yup packages.

Let us understand what error messages are and why they should be displayed to the user.

Seldom, a user enters incorrect values into the form fields, and you must have seen some error messages manifest on the screen. These messages help in hinting your users about their blunders.

As per the common notion, error messages play a vital role in such a scenario and help users easily determine the issue.

After that, users can quickly fix it and submit the form with absolutely no error.

How to Use React Hook Form to Show Validation Error Messages

  • Step 1: Set Up React Project
  • Step 2: Add Bootstrap Library
  • Step 2: Add Yup and Hook Form Plugins
  • Step 3: Create Form Component File
  • Step 4: List Form Module in App Js
  • Step 5: Run Development Server

Set Up React Project

First step tells you how to deal with blank React project installation.

On the terminal screen, you have to type the given command and quickly execute it.

npx create-react-app react-shine

Carefully enter into the project folder.

cd react-shine

Add Bootstrap Library

This instruction is for adding the bootstrap in React app. Now, you have to add the library so run the following command.

npm install bootstrap --legacy-peer-deps

Here, you have to include and use the bootstrap UI component in React.

Ensure that you are importing the bootstrap CSS path in App.js file.

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'

export default function App() {
  return (
    <>
     
    <>
  )
}

Add Yup and Hook Form Plugins

Let us install the yup and hook form plugins, you have to use the provided command to add the libraries.

npm install @hookform/resolvers yup --legacy-peer-deps

Create Form Component File

We are going to build a new component, this file will have the code to show error messages.

Therefore, open the component/ folder and make a new file inside the folder.

You can name it ErrorMsg.js file.

import React from 'react'

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


export default function ErrorMsg() {
  const yupValidation = Yup.object().shape({
    name: Yup.string()
      .required('Please enter some value.')
      .min(4, 'Add minimum 4 characters'),
    email: Yup.string().required('Email id is mendatory').email(),
  })

  const formOptions = { resolver: yupResolver(yupValidation) }

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

  const { errors } = formState

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

  return (
    <div className="container mt-4">
      <h2>React Integrate Validation Error Messages with Hook Form</h2>

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

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

List Form Module in App Js

This instruction is all about listing the error message component in React’s main app component file.

Hence, open the src/App.js and import the component as shown below.

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


export default function App() {
  return (
    <div className="App">
      <ErrorMsg />
    </div>
  )
}

Run Development Server

Lastly, you have to open the terminal again type the command and press enter.

npm start

Here is the url that you can use to check the app on the browser.

http://localhost:3000

React Display Validation Error Messages with Hook Form Tutorial

Conclusion

We built a simple form with only two input controls name and email.

And learned how to set validation error messages in React app using hook form and yup libraries.

Not just that, we also determine how to set form from the absolute beginning.