How to Validate Checkbox in JavaScript?

Validation of checkboxes is important to make sure that users select the required options, enhancing data accuracy and user experience.

Table of Content

  • Using a Loop
  • Using FormData Object

Using a Loop

In this approach, we are using a loop to iterate through each checkbox in the form. We check if any checkbox is checked, and if so, we collect its value into an array of selected options. If no checkboxes are checked, we display an error message prompting the user to select at least one option.

Example: The below example uses Loop to validate the checkbox in JavaScript.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
        .error-message {
            color: red;
        }
    </style>
</head>

<body>
    <h1 style="color: green;">w3wiki</h1>
    <h3>Approach 1: Using a Loop</h3>
    <form id="checkboxForm">
        <input 
                type="checkbox" 
                id="checkbox1"
                value="JAVA"> JAVA<br>
        <input 
                type="checkbox"
                id="checkbox2"
                value="Python">Python<br>
        <input 
                type="checkbox"
                id="checkbox3"
                value="CSS"> CSS<br>
        <button 
                type="button"
                onclick="approach1Fn()">Validate</button>
    </form>
    <p class="error-message" id="errorMessage"></p>
    <p id="selectedOptions"></p>
    <script>
        function approach1Fn() {
            const checkboxes = document
            .querySelectorAll('input[type="checkbox"]');
            let checked = false;
            let selectedOptions = [];
            checkboxes
                .forEach(checkbox => {
                    if (checkbox.checked) {
                        checked = true;
                        selectedOptions
                        .push(checkbox.value);
                    }
                });
            if (!checked) {
                document
                    .getElementById('errorMessage')
                    .textContent = 'Please select at least one option.';
                document
                    .getElementById('selectedOptions')
                    .textContent = '';
            } else {
                document
                    .getElementById('errorMessage')
                    .textContent = '';
                document
                    .getElementById('selectedOptions')
                    .textContent = 'Selected Options: ' + selectedOptions.join(', ');
            }
        }
    </script>
</body>

</html>

Output:

Validating the checkbox in JavaScript using loop

Using FormData Object

In this approach, we are using the FormData object to gather the checked status of checkboxes with the name “options[]”. By checking the length of the array of checked options, we determine if at least one option is selected, displaying an error message if not and listing the selected options otherwise.

Example: The below example uses FormData Object to validate the checkbox in JavaScript.

JavaScript
<!DOCTYPE html>
<html>

<head>
   <style>
      .error-message {
         color: red;
      }
   </style>
</head>

<body>
   <h1 style="color: green;">w3wiki</h1>
   <h3>Approach 2: Using FormData Object</h3>
   <form id="cbForm2">
      <input 
            type="checkbox"
            id="cb1" 
            name="options[]"
            value="GFG">GFG<br>
      <input 
            type="checkbox"
            id="cb2"
            name="options[]"
            value="Google"> Google<br>
      <input 
            type="checkbox"
            id="cb3"
            name="options[]"
            value="Meta">Meta<br>
   </form>
   <button 
            type="button"
            onclick="approach2Fn()">Validate</button>
   <p 
            class="error-message" 
            id="errorMessage5"></p>
   <p id="selectedOptions"></p>

   <script>
      function approach2Fn() {
         const formData = new FormData(document
         .getElementById('cbForm2'));
         const checkedOptions = formData
         .getAll('options[]');
         if (checkedOptions.length === 0) {
            document
            .getElementById('errorMessage5')
            .textContent = 'Please select at least one option.';
            document
            .getElementById('selectedOptions')
            .textContent = '';
         } else {
            document
            .getElementById('errorMessage5')
            .textContent = '';
            document
            .getElementById('selectedOptions')
            .textContent = 'Selected Options: ' + checkedOptions.join(', ');
         }
      }
   </script>
</body>

</html>

Output:

Validating the check box using the JavaScript loop



Contact Us