How to validate a checkbox list in React

You may need to validate a checkbox list when you are creating a form in React. Just as we have created a common component for the select field and radio button in the previous article, here we will create a component for the checkbox list in React.

Demo Application

Output - How to validate a checkbox list in React - Clue Mediator
Output – How to validate a checkbox list in React – Clue Mediator

Steps to validate a checkbox list in React

  1. Create a common component
  2. Create a form using common component
  3. Output

1. Create a common component

Let’s create a reusable checkbox list component using Bootstrap where we will pass all required fields.

Same as the Input component and Select component, we have to go through a few more props to handle the validation such as isReq, errorMsg, onValidateFunc.

Checkbox.js

Here we have updated the changeHandler function to store the selected values of the checkboxes.

2. Create a form using common component

Now it’s time to use the Checkbox component in the main component for language and hobbies selection. In the first place, we have to define two different state variables called form and error.

Let’s define the object for each property in an error state. The error object contains the following attributes.

  • isReq – For require validation
  • errorMsg – To render the error message on the screen
  • onValidateFunc – Function to handle the validation

In the above code, we have added a predefined value of the language. Now we have to slightly update the validateForm function as below.

Let’s use the following HTML to render the form in the React component.

Let’s write all the code together and see how it looks.

App.js

3. Output

Run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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