I have to validate a dropdown using required validation in AngularJS. I have created directives for validation but directive is not loaded on select tag. How to load directive on dropdown? Or, how to validate a dropdown?
You can add a validation method on the submit button of your form to check the value of your dropdown.
Example : http://plnkr.co/edit/PbePIh
app.js :
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.colors = [{name: 'blue'}, {name:'red'}, {name:'yellow'}];
$scope.reqColor = function() {
if ($scope.color && $scope.color.name && $scope.color.name != 'blue') return false;
return true;
}
});
index.html :
<body ng-controller="MainCtrl">
<form name="form">
<select ng-model="color" ng-options="c.name for c in colors"></select><br>
<button ng-disabled="form.$invalid || reqColor()">Save</button>
</form>
</body>
In this example, the save button will be disabled if you didn't select anything in the dropdown or if you selected the color blue.