skip to content

HTML: Validating a checkbox with HTML5

 Tweet3 Shares0 Tweets

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 type="text/javascript"> function checkForm(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>
Example 1

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 with 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:

Example 2

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.

At time of writing Safari does not enforce required input fields. If you're using Safari or another unsupporting browsers all the examples will just display the JavaScript alert box.

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 onchange="this.setCustomValidity(validity.valueMissing ? 'Please indicate that you accept the Terms and Conditions' : '');" id="field_terms" type="checkbox" required name="terms"> I accept the <u>Terms and Conditions</u></p> <p><input type="submit"></p> </form> <script type="text/javascript"> 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.

Example 3

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 determing the right message. 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 the JavaScript to reinstate the event handlers:

<script type="text/javascript"> document.addEventListener("DOMContentLoaded", function() { var myForm = document.getElementById("example4"); var checkForm = function(e) { ... if(!this.terms.checked) { alert("Please indicate that you accept the Terms and Conditions"); this.terms.focus(); e.preventDefault(); // equivalent to return false return; } }; // attach the form submit handler myForm.addEventListener("submit", checkForm, true); var myCheckbox = document.getElementById("field_terms"); var myCheckboxMsg = "Please indicate that you accept the Terms and Conditions"; // set the starting error message myCheckbox.setCustomValidity(myCheckboxMsg); // attach checkbox handler to toggle error message myCheckbox.addEventListener("change", function() { this.setCustomValidity(this.validity.valueMissing ? myCheckboxMsg : ""); }, false); }, false); </script>

The forms behaviour should be unchanged:

Example 4

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 exept for Safari which ignores the requirement.

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 type="text/css"> 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 type="text/css"> 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.

Did you find any of these examples useful or have any questions? Let us know using the Feedback form below.

References

< HTML

Send a message to The Art of Web:


used only for us to reply, and to display your gravatar.

CAPTCHA

<- copy the digits from the image into this box

press <Esc> or click outside this box to close

User Comments

Post your comment or question

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.

top