On various websites, a square-shaped box called a “checkbox” appears to accept all the terms and conditions before submitting a form. Similarly, the checkboxes are used in specific forms of information gathering, such as surveys, to get the users’ opinions. The validation of the checkboxes helps to ensure that the checkbox is marked or checked. It will be helpful to improve the user experience by alerting the user to any errors in the form before they are submitted.
To perform checkbox validation, use the “checked” property of the checkbox element. If the checkbox is checked, it gives “true” else, it returns “false” for the “not-checked” checkbox.
Create a checkbox in the form and submit it by marking or checking the checkbox. If you try to submit the form without checking the checkbox (accepting the terms and conditions), it will throw an error, and the form will not be submitted:
<input type="checkbox" id="accept"> I accept all the terms and conditions<br>
<br><input type="button" value="Submit" onClick="validation()">
Define a function “validation()” to validate the checkbox by showing an error message while submitting the form without marking the checkbox:
var checkbox = document.getElementById("accept");
document.getElementById("error").innerHTML = "You must accept the terms and conditions by checking the Checkbox";
document.getElementById("error").innerHTML = "Thanks....";
In the above-given code:
- First, get the reference of the checkbox using its id.
- Then, check whether the checkbox is checked/marked utilizing the “checked” property.
- If the checkbox is not marked, show an error message and ask to mark the check box for submitting the form.
You can also use the syntax below to check whether the checkbox is marked: