HTML: Validating a checkbox with HTML5
While HTML5 form validation is typically about missing or invalid text inputs, there are other form element types that also require attention. One of them being the humble checkbox.
Checkbox validation using JavaScript
Suppose you have a form on your website that at the bottom asks people to "accept the Terms and Conditions" or something similar. Basically you don't want the form to be submitted unless this is checked.
Using vanilla JavaScript we can prevent form submission as follows:
<script>
var checkForm = function(form) {
...
if(!form.terms.checked) {
alert("Please indicate that you accept the Terms and Conditions");
form.terms.focus();
return false;
}
return true;
};
</script>
<form ... onsubmit="return checkForm(this);">
...
<p><input type="checkbox" name="terms"> I accept the <u>Terms and Conditions</u></p>
<p><input type="submit"></p>
</form>
All this does is confirm before submitting the form that the checkbox is checked. If not, an alert is displayed and focus is moved to the checkbox. Not the prettiest solution, but functional in all browsers that have JavaScript enabled.
HTML5 required input
Adding HTML5 validation to the checkbox is actually very simple. All you need to do is include a required attribute:
<form ... onsubmit="return checkForm(this);">
...
<p><input type="checkbox" required name="terms"> I accept the <u>Terms and Conditions</u></p>
<p><input type="submit"></p>
</form>
This tells the browser that the form should not be allowed to submit without the checkbox checked. Some, but not all, browsers will recognise and enforce this:
The advantage of the HTML5 form validation is that it happens before our JavaScript is called, displays instructions and points the user to the relevant element.
Here you can see screen captures from Firefox and Chrome:
Text alert messages are generated entirely by the browser and will even translate automatically into different languages - something that would be almost impossible using just JavaScript.
The advantage for the user is that it's obvious whick element is causing the problem and there's no alert window that needs to be clicked away.
If you're using an unsupporting browsers all the examples will just display the JavaScript alert box after ignoring the HTML5 validation.
Customised HTML5 messages
As you would hope it is possible to customise the messages that are displayed by the browser with your own text, but this can only be done via JavaScript. You need to check the validity state of the element yourself and set (and clear) the message explicitly:
<form ... onsubmit="return checkForm(this);">
...
<p><input id="field_terms" onchange="this.setCustomValidity(validity.valueMissing ? 'Please indicate that you accept the Terms and Conditions' : '');" type="checkbox" required name="terms"> I accept the <u>Terms and Conditions</u></p>
<p><input type="submit"></p>
</form>
<script>
document.getElementById("field_terms").setCustomValidity("Please indicate that you accept the Terms and Conditions");
</script>
The block of JavaScript below the form is assigning our custom error message to the checkbox when the page loads. We know that the checkbox is unchecked by default so we need to tell the browser what message to display.
The onchange event handler on the checkbox then toggles the error message. When the checkbox is valid (checked) the message is set to blank which tells the browser that it's ok for the form to be submitted.
When the checkbox is not checked and the Submit button is clicked an alert is displayed similar to the examples above, but using our text instead of the default.
Here you can see the custom message being displayed in Firefox:
Custom messages can be set in a similar manner for text and other elements, but you will need to check the validity object states (validity.valueMissing | validity.patternMismatch | ...) to determine the current message to display. See the link under References for details.
Separating FORM from function
The previous example was starting to become a bit cluttered with two JavaScript script blocks as well as the onsubmit and onchange event handlers inlined in the HTML.
We can separate the JavaScript code from the HTML and have the required event handlers assigned after the page has loaded using an onload event listener.
Here first is the HTML with all JavaScript removed:
<form id="example4" ...>
...
<p><input id="field_terms" type="checkbox" required name="terms"> I accept the <u>Terms and Conditions</u></p>
<p><input type="submit"></p>
</form>
And then the JavaScript to reinstate the event handlers:
<script>
window.addEventListener("DOMContentLoaded", (e) => {
const checkForm = (e) => {
const form = e.target;
...
if(!form.terms.checked) {
alert("Please indicate that you accept the Terms and Conditions");
form.terms.focus();
e.preventDefault();
return; /* equivalent to return false */
}
};
const myForm = document.querySelector("#example4");
const myCheckbox = myForm.querySelector("#field_terms");
const myCheckboxMsg = "Please indicate that you accept the Terms and Conditions";
/* attach the form submit handler */
myForm.addEventListener("submit", checkForm);
/* set the starting error message */
myCheckbox.setCustomValidity(myCheckboxMsg);
/* attach checkbox handler to toggle error message */
myCheckbox.addEventListener("change", (e) => {
let el = e.target;
el.setCustomValidity(el.validity.valueMissing ? myCheckboxMsg : "");
});
});
</script>
The forms behaviour should be unchanged:
While it looks much more complicated, this is a better solution because it allows for the HTML and JavaScript to be maintained separately. The only hooks between them are the id values for the form itself and the checkbox input element. Also gone are any globally defined functions or variables.
The JavaScript can now be moved to a separate file, or converted to a code library allowing for it to be reused with other forms.
The required attribute on checkboxes is supported in
Internet Explorer 10 and most/all other browsers except for
Safari which currently ignores it.
CSS3 required styles
As we've see in other articles the valid/invalid state of a form element can be used to provide visual feedback to the user - displaying a green thumbs up or checkmark for example when the input requirements have been satisfied, or displaying a red outline or warning symbol when they have not.
This is also possible with checkbox elements, just a bit trickier because you can't really place anything on the inside.
Here's some sample code to get you started:
<style>
input[type="checkbox"]:required:invalid + label {
color: red;
}
input[type="checkbox"]:required:valid + label {
color: green;
}
</style>
<form ...>
...
<p><input id="field_terms" type="checkbox" required name="terms">
<label for="field_terms">I accept the <u>Terms and Conditions</u></label></p>
...
</form>
The CSS depends of course on how you mark up form fields. In this case we've included a label element alongside the checkbox which allows us to reference it using the CSS3 adjacent sibling selector. These styles are all being applied to the label element.
Clicking on the checkbox or the label text will now toggle the checkbox state, and the text will change from red to green. Basically, when the checkbox is happy, the label is happy.
There are also clever ways of styling the label to look like a checkbox and hiding the actual checkbox so you can use your own graphic, font icon or CSS creation:
<style>
input[type="checkbox"]:required {
display: none;
}
input[type="checkbox"]:required:invalid + label::before {
content: "\2610";
padding-right: 0.2em;
font-size: 1.6em;
color: red;
}
input[type="checkbox"]:required:valid + label::before {
content: "\2611";
padding-right: 0.2em;
font-size: 1.6em;
color: green;
}
</style>
In this case we've used some UNICODE 'ballot box' characters for the on/off state. They are prepended to the label, but actually toggling the checkbox in the background. We know the checkbox is changing because that's what drives the CSS effect:
The HTML for this example is the same as above.
For more examples like this check out our new article Styling a Yes/No Checklist with CSS.
Did you find any of these examples useful or have any questions? Let us know using the Feedback form below.
References
Related Articles - Form Validation
- HTML HTML5 Form Validation Examples
- HTML Validating a checkbox with HTML5
- JavaScript Preventing Double Form Submission
- JavaScript Counting words in a text area
- JavaScript Date and Time
- JavaScript Password Validation using regular expressions and HTML5
- JavaScript Tweaking the HTML5 Color Input
- JavaScript Credit Card numbers
- JavaScript A simple modal feedback form with no plugins
- JavaScript Form Validation
- JavaScript Allowing the user to toggle password INPUT visibility
- PHP Measuring password strength
- PHP Protecting forms using a CAPTCHA
- PHP Basic Form Handling in PHP
- PHP Creating a CAPTCHA with no Cookies
J Miller 23 July, 2020
Loved the HTML5 checkbox form validation. Work perfectly! Thanks!!
Nick 1 November, 2019
Just wanted to let you know, that HTML5 validation is not working with checkbox stylings, because the input element is then hidden.
But thanks for the overview!
Best regards
Nick
shayne 3 December, 2016
Hey...
I'm not much of a developer, but stubble on your website searching for exactly what you posted here. However, I noticed that your script is throwing errors and thought maybe i'd check with you to see if you might know why.
First.. I'm getting :
Uncaught SyntaxError: Unexpected token ...
and then about 4 of these:
Uncaught TypeError: Cannot read property 'addEventListener' of null(...)
Anyways, just thought I'd see if you knew why. Anyways, may just switch over to a wp plugin, but thought I'd try to sharpen up my development skills a little lol
Cheers!
It sounds like you've copied what's on the page verbatim, including one or more "..." placeholders. And you may be referencing a form "example4" without having a form with that id on the page.