React 18 Hook Form 7 Required Checkbox Validation Tutorial

Last Updated on by in React JS

Creating checkboxes in React is not so difficult, especially when you are using React Hook Form library.

Even the checkbox validation is also simplistic with a Yup JavaScript schema builder.

This guide will ensure how to include required validation in React checkboxes components.

We will explain every process step by step, from integration to validation, and we have simplified everything.

In order to build the checkbox module, you will use the useForm module; besides, for implementing the required validation, you will be using Yup and yupResolver modules.

How to Add Required Validation in React Checkbox and Show Error Message.

  • Step 1: Construct React Project
  • Step 2: Add Bootstrap UI Package
  • Step 3: Install Yup and Hook Form Libraries
  • Step 4: Build Hook Form Checkbox Component
  • Step 5: Register Module in App Js
  • Step 6: Run Development Server

Construct React Project<

Start with constructing a brand new React application. The following command will generate a blank new Rect application.

Open the terminal window, type the command and hit enter to commence the installation process.

npx create-react-app react-gem

Now, move into the project folder.

cd react-gem

Add Bootstrap UI Package

In this step, you will be adding bootstrap UI design package in React application.

Ensure that you execute the given command through terminal.

npm install bootstrap --legacy-peer-deps

Install Yup and Hook Form Libraries

On the other hand, we need a couple of packages that will help us set up the checkbox in the React form.

Those packages are hook form and yup schema validation.

You need to invoke the suggested command, and it will simultaneously install both libraries.

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

Build Hook Form Checkbox Component

In the following step, you need to enter into the component/ directory, here you also have to make the new file, name it CustomCheckbox.js.

Do not forget to paste the given code into the CustomCheckbox.js file.

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


export default function CustomCheckbox() {
  const validation = Yup.object().shape({
    chooseCb: Yup.bool().oneOf([true], 'Checkbox selection is required'),
  })

  const optionsForm = { resolver: yupResolver(validation) }

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

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

  return (
    <div className="container mt-3">
      <h2>Required Make Checkbox in React Example</h2>

      <form onSubmit={handleSubmit(onCbFormSubmit)}>
        <div className="form-group">
          <div className="form-check">
            <input
              type="checkbox"
              name="selectCheckbox"
              id="selectCheckbox"
              {...register('chooseCb')}
              className={`form-check-input ${
                errors.chooseCb ? 'is-invalid' : ''
              }`}
            />

            <label htmlFor="chooseCb" className="form-check-label">
              Are you sure?
            </label>

            <div className="invalid-feedback">{errors.chooseCb?.message}</div>
          </div>
        </div>
        <div className="mt-3">
          <button type="submit" className="btn btn-dark">
            Send
          </button>
        </div>
      </form>
    </div>
  )
}

Register Module in App Js

Let us move on to App.js file, you have to register the checkbox module in this file.

Next, you have to append the code into the file.

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


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

Run Development Server

In the final step, you will be running the application’s development server.

npm start

Here is the url that you need to execute to see the app in action.

http://localhost:3000

React Hook Form 7 Required Checkbox Validation Tutorial

Conclusion

In general, a checkbox is a simple UI element, a square box that has two states. Checked and unchecked simply refers to activated or unactivated.

It allows users to select either one or multiple options from a limited number of options.

In this tutorial, we have seen how to create and incorporate required validation in the Checkbox within React application.