React Tutorial- Display Validation Error Messages With Hook Form

Display Validation Error Messages With Hook Form

Before developing a React app, it is mandatory to understand how important it is to implement validation in form. A form may hold one or more than one input elements.

We should definitely show reverence to proper handling if we want to get the user-provided data in a subtle manner.

Throughout this guide, we will get to learn how to add validation in React and to show appropriate error messages in React app using Hook and Yup packages.

 

It should also be understood what are error messages and why they should be displayed to the user.

Sometimes, it happens that a user enters incorrect values into the form fields and we must have seen some error messages manifest on the screen. These messages help in hinting the users about their blunders.

So, error messages play a significant 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 3- Add Yup And Hook Form Plugins

Step 4- Create Form Component File

Step 5- List Form Module In App Js

Step 6- Run Development Server

 

Now, let’s learn in detail:

Step 1- Set Up New React Project

The very first step is to install a blank React project for which we will type the following command on the terminal and then, execute it:

npx create-react-app react-shine

Afterward, we will enter into the project folder:

cd react-shine

 

Step 2- Add Bootstrap Library

In this second step, we will add the bootstrap in the React app. So, we will add the library by running the following command:

npm install bootstrap

Now, we need to include and use the bootstrap UI component in React. Do remember to import the bootstrap CSS path in App.js file:

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

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

 

Step 3- Add Yup And Hook Form Plugins

Here, we have to install the yup and hook form plugins by using the provided command to add the libraries:

npm install @hookform/resolvers yup

 

Step 4- Create Form Component File

In this step, we will have the code to show error messages by building a new component.

So, we need to open the component/ folder and make a new file inside the folder. WE 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>
  )
}

 

Step 5- List Form Module In App Js

By following this instruction, we will list the error message component in React’s main app component file.

For this, we will 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>
  )
}

 

Step 6- Run Development Server

In this last step, we have to open the terminal again to type the given command and hit enter:

npm start

 

Conclusion

In this tutorial, we built a simple form with only two input controls name and email. And also, learned how to set validation error messages in react app using yup and hook form libraries.

 

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *