HTML.form.guide

How to do multiple checkbox validation in Javascript

checkbox validations javascript validation required validation

Checkboxes can be used as a single checkbox (like an on-ff switch) or as a group of checkboxes where the user can select one or more options.

How do we do validations when you have multiple checkboxes? Here are some samples.

At least one checkbox should be checked (Required validation)

In the validation code, we extract the FormData object from the form element.

Then use the FormData method to check the presence of the checkbox value.

function handleData()
{
    var form_data = new FormData(document.querySelector("form"));
    if(!form_data.has("langs[]"))
    {
        document.getElementById("chk_option_error").style.visibility = "visible";
    }
    else
    {
        document.getElementById("chk_option_error").style.visibility = "hidden";
    }
    return false;
}

Check whether at least 2 options are selected

In case you want at least two options selected, you can modify the check a little bit like this:

if(form_data.getAll("langs[]").length < 2)
{
    //show error
}
else
{
    //no error
}

See Also