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
- Checkbox checked validation using JavaScript
- Checkbox validation using jQuery
- HTML Form Checkbox with required validation
- Google reCaptcha 2 JavaScript Validation (client side)
- Custom styled checkboxes with Bootstrap
- HTML Form with Checkboxes examples and sample code
- How to create a dropdown with checkbox options with Bootstrap Style
- How to create checkbox in Bootstrap style ?
- How to get checkbox value in form submission