I recently needed to validate how many checkboxes a user checks on one of my forms. I decided to use the Spry checkbox validation widget. The checkbox validation widget can display error messages if a user fails to select a minimum number of checkboxes or selects more than the maximum allowed number of checkboxes. The widget can validate the form when the user clicks on the submit button or when the user changes a checkbox. Since the demo provided by Adobe for this widget doesn't show some of the different ways to use the checkbox validation widget I thought I would provide an example of the different ways you may use this widget.
There are two files you must include in the page where you want to use the checkbox widget:
Both files are available in the Spry 1.5 library download. Check my example for how you can include these files on your web page.
The checkbox widget documentation provides a good overview on how to set up your web page and form to use the checkbox widget. Basically, you follow three general steps:
- Include the two files mentioned above
- Surround your checkbox(es) with a div or span tag that has a specific id value (for example checkBoxWidget)
- Create the checkbox widget at the end of your page using the id value (for example checkBoxWidget) and provide any values for the checkbox widget options
Concerning step 3 above, there are a few options you may want to use with the checkbox widget. For example if you want to ensure the user checks a minimum number of checkboxes and also doesn't check more than a maximum number of checkboxes, you need to specify those values when you create the checkbox widget. For example:
Also, the default event for the checkbox widget to act upon is the submit event. If you want the checkbox widget to validate each time the user checks (or unchecks) a checkbox then you need to specify the change event. For example:
Another option you may want to use is to allow the user to check none of the checkboxes. The following example creates a checkbox widget that will validate if the user selects no check boxes or if the user selects 2 or less checkboxes.
You can change the CSS in the SpryValidationCheckBox.css file to style the error message in the manner you prefer. In my example, I'm using an exclamation point image to appear before the error message. The Adobe checkbox widget example (see reference 3) provides another example of changing the default style of the error messages.
Again view my example, its source code, and the references above for how to use the Spry checkbox validation widget. I think you'll find it easy to use.