Skip to content
This repository has been archived by the owner on Sep 5, 2024. It is now read-only.

Commit

Permalink
fix(select): Fail validation if selection is not a valid option.
Browse files Browse the repository at this point in the history
The md-select currently passes validation even if the model is
not one of the provided options.

Fixes #7954.

Closes #7989
  • Loading branch information
topherfangio authored and ThomasBurleson committed Jun 2, 2016
1 parent 7f776a1 commit da02ea2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/components/select/select.js
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,11 @@ function SelectMenuDirective($parse, $mdUtil, $mdTheming) {
self.ngModel = ngModel;
self.modelBinding = binding;

// Setup a more robust version of isEmpty to ensure value is a valid option
self.ngModel.$isEmpty = function($viewValue) {
return !self.options[$viewValue];
};

// Allow users to provide `ng-model="foo" ng-model-options="{trackBy: 'foo.id'}"` so
// that we can properly compare objects set on the model to the available options
if (ngModel.$options && ngModel.$options.trackBy) {
Expand Down
23 changes: 23 additions & 0 deletions src/components/select/select.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,29 @@ describe('<md-select>', function() {
expect($rootScope.testForm.$valid).toBe(false);
}));

it('properly validates required attribute based on available options', inject(function($rootScope, $compile) {
var template =
'<form name="testForm">' +
' <md-select ng-model="model" required="required">' +
' <md-option ng-repeat="opt in opts" ng-value="opt"></md-option>' +
' </md-select>' +
'</form>';

$rootScope.opts = [1, 2, 3, 4];

$compile(template)($rootScope);

// Option 0 is not available; should be false
$rootScope.model = 0;
$rootScope.$digest();
expect($rootScope.testForm.$valid).toBe(false);

// Option 1 is available; should be true
$rootScope.model = 1;
$rootScope.$digest();
expect($rootScope.testForm.$valid).toBe(true);
}));

it('should keep the form pristine when model is predefined', inject(function($rootScope, $timeout, $compile) {
$rootScope.model = [1, 2];
$rootScope.opts = [1, 2, 3, 4];
Expand Down

0 comments on commit da02ea2

Please sign in to comment.