In this article I will explain with an example, how to validate Group of RadioButtons (Multiple RadioButtons) using AngularJS.
When the Submit Button is clicked, the Model for each RadioButton in the Group will be referenced and using FOR loop, it will be validated that one RadioButton is checked from the Group of RadioButtons using AngularJS.
Validating Group of RadioButtons (Multiple RadioButtons) using AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The AngularJS app HTML DIV consists of an HTML Table with a Group of RadioButtons to be validated, an HTML SPAN for displaying the error message and a HTML Button.
The ng-repeat directive has been applied to the TBODY tag of the HTML Table in order to populate Group of CheckBoxes from a JSON array.
The ng-model attribute of the RadioButton has been assigned the Selected property. Thus whenever a RadioButton is selected, the Selected property for the corresponding object in the JSON array will be set to TRUE.
The Button has been assigned ng-click directive. When the Button is clicked, the Submit function of the Controller gets called.
Inside the function, a FOR loop is executed over the JSON array and the Selected property of each RadioButton is verified whether it is True.
If at-least one RadioButton is checked, then the validation is successful else an error message is displayed using AngularJS.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.IsValid = null;
$scope.Fruits = [{
FruitId: 1,
Name: 'Mango',
Selected: false
}, {
FruitId: 2,
Name: 'Apple',
Selected: false
}, {
FruitId: 3,
Name: 'Banana',
Selected: false
}, {
FruitId: 4,
Name: 'Grapes',
Selected: false
}, {
FruitId: 5,
Name: 'Orange',
Selected: false
}];
$scope.Submit = function () {
$scope.IsValid = false;
for (var i = 0; i < $scope.Fruits.length; i++) {
if ($scope.Fruits[i].Selected) {
$scope.IsValid = true;
break;
}
}
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<table id="Table1" border="0" cellpadding="0" cellspacing="0">
<tbody ng-repeat="fruit in Fruits">
<tr>
<td>
<input type="radio" name = "Fruit" value="{{fruit.FruitId}}" ng-model="fruit.Selected" />
</td>
<td>
{{fruit.Name}}
</td>
</tr>
</tbody>
</table>
<br />
<span id="spnError" class="error" ng-hide="IsValid == null || IsValid">Please select a Fruit.<br /></span>
<br />
<input type="button" value="Submit" ng-click="Submit()" />
</div>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads