QuizCure
Find Available Solution Here!

Checkbox Validation in Javascript

Deepak Apr 25, 2024

In this article, we will go through validations for checkbox in following a step-by-step approach

  • Single checkbox validation in javascript How to make group checkbox mandatory
  • Multiple checkboxes at least n required

Let's dive into the following sample code example that demonstrates the above-mentioned steps to cover a current topic about checkbox validation in javascript

Single checkbox validation in javascript

Let's go through the below-mentioned code block to understand single checkbox validation:

Html Form

<form name="demo" method="POST" onsubmit="return validateForm(this);">
    <div id="msg"> </div>
    <div> Email <input type="text" name="email" value=""></div>    
    <div><input type="checkbox" name="terms"> I accept the Terms </div>
    <div><input type="submit" name="submit" value="SignUp"></div>
</form>

Javascript Validation Code for checkbox:

    function validateForm(form) {

        var isChecked = form.terms.checked;
        
        if (!isChecked) {
            document.getElementById("msg").innerHTML = "Please Accept Terms";
            return false;
        }
        return true;
    }
 

Here is What code means:

  • Let's suppose we have a SignUp form containing the terms checkbox and email text box.
  • Submit event triggers once we submit our form. We have attached a form validation method against the submit event handler. It means if the calling method validateForm returns true then the form will submit otherwise it won't submit.
  • Here a checkbox checked properly is used to check whether a checkbox is checked or not. Therefore form.terms.checked will return true if the checkbox is checked else returns false.
  • Prompting validation message to user if term checkbox is not checked by displaying error message within div with id as msg with the help of code document.getElementById("msg").innerHTML = "Please Accept Terms";

How to make group checkbox mandatory?

Here a group of checkboxes means a collection of single Checkboxes. Let's suppose we have formed with a group of different departments as below

<form name="department" method="POST" onsubmit="return validateForm(this);">
    <div id="msg"> </div>
    <div>
        <input type="checkbox" name="department[]" value="IT"> IT 
        <input type="checkbox" name="department[]" value="Finance"> Finance 
        <input type="checkbox" name="department[]" value="HR"> HR 
        <input type="checkbox" name="department[]" value="Legal"> Legal 
    </div>
    <div><input type="submit" name="submit" value="SignUp"></div>
</form>

Now, We won't allow users to submit forms without providing department input. Following javascript multiple checkbox code help to avoid empty checkbox form submission.

Validation code:

    function validateForm(form) {

        var departmentGroup =  document.getElementsByName("department[]");

        var checkedDepartment = 0
        
        for (var i = 0; i < departmentGroup.length; i++) {
            if (departmentGroup[i].checked) {
                checkedDepartment++;
            }
        }

  
        if (checkedDepartment == 0) {
            document.getElementById("msg").innerHTML = "Department is required field!";
            return false;
        }
        return true;
    }

Code Explanation:

  • First, find the length of the group of department checkboxes.
  • we can use the checked attribute to ensure whether the checkbox is checked or not. Therefore the departmentGroup[0] in the above code represents the first checkbox and departmentGroup[1] represents seconds and so on. Code departmentGroup[0].checked return true if checked otherwise return false.
  • Based on concepts as described in step 2 we can check for n number of checkboxes by looping through until the length of multiple checkboxes.
  • Variable checkedDepartment is incremented for each checked checkbox. checkedDepartment will be 0 if none is checked.
  • Display error message to user once checkedDepartment is 0.

Multiple checkboxes at least N required

There can be a scenario where we want users to choose

  • multiple checkboxes at least 1
  • multiple checkboxes at least 2
  • multiple checkboxes at least N

In such a case, we will use the same previously explained validation code. Suppose in the previous example we need the user to select at least 2 checkboxes.

Just we need to change the alert condition as below

  if (checkedDepartment < 2) {
            document.getElementById("msg").innerHTML = "At Least two Department should be chosen";
            return false;
        }
 

In such a way we can make a mandatory selection for N number as well

Was this post helpful?

Send Feedback

Connect With QuizCure


Follow Us and Stay tuned with upcoming blog posts and updates.

Contributed By

Deepak

Deepak

QC STAFF
51 Posts
  • PHP
  • JAVA
  • PYTHON
  • MYSQL
  • SEO

You May Like to Read

Scroll up