Validating Radio Buttons

Contact Us or call 1-877-932-8228
Validating Radio Buttons

Validating Radio Buttons

Radio buttons that have the same name are grouped as arrays. Generally, the goal in validating a radio button array is to make sure that the user has checked one of the options. Individual radio buttons have the checked property, which is true if the button is checked and false if it is not. The example below shows a simple function for checking radio button arrays.

Code Sample:

<meta charset="UTF-8">
<title>Radio Arrays</title>
<script type="text/javascript">
function validate(form){
	var errors = [];
	if ( !checkRadioArray(form.container) ) {
		errors[errors.length] = "You must choose a cup or cone.";
	if (errors.length > 0) {
		return false;
	return true;

function checkRadioArray(radioButtons){
	for (var i=0; i < radioButtons.length; i++) {
		if (radioButtons[i].checked) {
			return true;
	return false;

function reportErrors(errors){
	var msg = "There were some problems...\n";
	var numError;
	for (var i = 0; i<errors.length; i++) {
		numError = i + 1;
		msg += "\n" + numError + ". " + errors[i];
<h1>Ice Cream Form</h1>
<form method="post" action="Process.html" 
			onsubmit="return validate(this);">
	<strong>Cup or Cone?</strong>
	<input type="radio" name="container" value="cup"> Cup
	<input type="radio" name="container" value="plaincone"> Plain cone
	<input type="radio" name="container" value="sugarcone"> Sugar cone
	<input type="radio" name="container" value="wafflecone"> Waffle cone
	<input type="submit" value="Place Order">


The checkRadioArray() function takes a radio button array as an argument, loops through each radio button in the array, and returns true as soon as it finds one that is checked. Since it is only possible for one option to be checked, there is no reason to continue looking once a checked button has been found. If none of the buttons are checked, the function returns false.

We'll go over this code in more details in the upcoming presentation