React Tutorial- Display Validation Error Messages With Hook Form

React Tutorial- Display Validation Error Messages With Hook Form

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

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

In this tutorial, we will get to know in this guide how to add validation in React, show appropriate error messages in React application using Hook Form and Yup packages.

 

Now, let’s see what error messages are and why they should be displayed to the user.

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

So now, it is quite clear that error messages play an important role in such a situation and help the users easily determine the issue. And after that, the user can immediately fix it and form with no error in it.

 

How To Use Error Hook Form To Show Validation Error Message

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 React Project

The very first and basic step is to install a new React project. For this, we have to type the given command on the terminal screen and execute it:

npx create-react-app react-shine

Afterward, we enter into the project folder:

cd react-shine

 

Step 2- Add Bootstrap Library

Now, in this step, we will execute the following instruction for adding the bootstrap in React app. We have to run the given command:

npm install bootstrap

Gere, we will include and use the bootstrap UI component in React. Do remember to import the bootstrap CSS 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

In the third step, we have to install the yup and hook form plugins. So, we have to use the given command to add the libraries:

npm install @hookform/resolvers yup

 

Step 4- Create Form Component File

Now, we will build a new component. This file will have the code to show error messages.

That is why, we 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

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

Hence, we have to open src/App.js and import the component as given 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 The Server

The last step is to open the terminal again for which we type the following command and hit enter:

npm start

 

Conclusion

So, in this tutorial, we have seen to build 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.

 

Thanks

Leave a Reply

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