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

Commit

Permalink
fix(select): form remains valid after empty option is selected
Browse files Browse the repository at this point in the history
- change md-select's `$isEmpty()` implementation from a naive falsy check
  to a more robust check that is similar to AngularJS' default
- add empty option to validations demo

Fixes #10005
  • Loading branch information
Splaktar committed Dec 16, 2020
1 parent 5f8472c commit 61412b4
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
1 change: 1 addition & 0 deletions src/components/select/demoValidations/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<md-input-container flex="50">
<label>Favorite Color</label>
<md-select name="favoriteColor" ng-model="favoriteColor" required>
<md-option value=""></md-option>
<md-option value="red">Red</md-option>
<md-option value="blue">Blue</md-option>
<md-option value="green">Green</md-option>
Expand Down
9 changes: 6 additions & 3 deletions src/components/select/select.js
Original file line number Diff line number Diff line change
Expand Up @@ -589,8 +589,8 @@ function SelectDirective($mdSelect, $mdUtil, $mdConstant, $mdTheming, $mdAria, $

function inputCheckValue() {
// The select counts as having a value if one or more options are selected,
// or if the input's validity state says it has bad input (eg string in a number input)
// we must do this on nextTick as the $render is sometimes invoked on nextTick.
// or if the input's validity state says it has bad input (eg: string in a number input).
// We must do this on nextTick as the $render is sometimes invoked on nextTick.
$mdUtil.nextTick(function () {
containerCtrl && containerCtrl.setHasValue(
selectMenuCtrl.getSelectedLabels().length > 0 || (element[0].validity || {}).badInput);
Expand Down Expand Up @@ -850,7 +850,10 @@ function SelectMenuDirective($parse, $mdUtil, $mdConstant, $mdTheming) {
self.ngModel.$isEmpty = function($viewValue) {
// We have to transform the viewValue into the hashKey, because otherwise the
// OptionCtrl may not exist. Developers may have specified a trackBy function.
return !self.options[self.hashGetter($viewValue)];
var hashedValue = self.options[self.hashGetter($viewValue)] ? self.options[self.hashGetter($viewValue)].value : null;
// Base this check on the default AngularJS $isEmpty() function.
// eslint-disable-next-line no-self-compare
return !angular.isDefined(hashedValue) || hashedValue === null || hashedValue === '' || hashedValue !== hashedValue;
};

// Allow users to provide `ng-model="foo" ng-model-options="{trackBy: '$value.id'}"` so
Expand Down

0 comments on commit 61412b4

Please sign in to comment.