Web Matters

Javascript form validation - checkboxes

This page is a sequel to my page Javascript form validation - doing it right, which has proved to be remarkably popular. A correspondent suggested that I could do something on the validation of checkboxes.

Validation of checkboxes is not usually needed. After all, the reader can only select the options which the author has provided. However sometimes the intention may be to select a particular number of options: to check 3 boxes out of 10 for example. In this case Javascript validation can be useful.

The principles of validation are almost the same as I have given on the previous page, so I won’t repeat them. The one difference is that it is not helpful to try to validate checkboxes at the moment they are checked; it is best left until submission time.

The validateCheckbox routine in the code assumes that multiple checks are required. This is because if you want the reader to select just one option, radio buttons are a much easier way of achieving the same result. The code makes it possible to enforce exactly N checks, or a maximum of N, or a minimum of N.

One curious case is when you want the reader to check a single box. This might at first glance seem pointless, but apparently the lawyers of the world have decided this is a good way of enforcing terms and conditions. This requires slightly different code, as a single checkbox is not treated as an array of one element. (Actually a probably better solution would be to use two radio buttons: “I do not accept” and “I accept” with the former set as the default. Then no script is needed.)

A small example follows.


Enter organisation:
Faster:
Better:
Cheaper:
Choose two.

The terms and conditions for using this site have been deposited in a locked safe buried three metres under a polar bear’s snowhole in Thule, Greenland. Please confirm you have read them and agree to them.