HTML.form.guide

HTML Form Checkbox with required validation

The code below shows how to create a single checkbox with “required” validation. Make sure you have not selected the checkbox and then press the submit button to see the error message.

Required Validation for a group of checkboxes

Although the HTML5 ‘required’ validation will work fine with Single checkboxes, there is no HTML5 validation for a group of checkboxes. You will have to do the validation using Javascript.

Here is the validation function for more clarity:

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; } 

The function collects the FormData() from the form element and check for langs variable. If none of the options are selected, the langs options should be empty.

See Also