Skip to content

Commit

Permalink
fix(select): invalidate when 'multiple, required and model is []`
Browse files Browse the repository at this point in the history
When `multiple` attribute is set on a `<select>` control and the model value is an empty array,
we should invalidate the control.  Previously, this directive was using incorrect logic for
determining if the model was empty.

Closes angular#5337
  • Loading branch information
Caitlin Potter authored and petebacondarwin committed Dec 17, 2013
1 parent b2e472e commit 5c97731
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
14 changes: 3 additions & 11 deletions src/ng/directive/select.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,18 +221,10 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);

// required validator
if (multiple && (attr.required || attr.ngRequired)) {
var requiredValidator = function(value) {
ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
return value;
if (multiple) {
ngModelCtrl.$isEmpty = function(value) {
return !value || value.length === 0;
};

ngModelCtrl.$parsers.push(requiredValidator);
ngModelCtrl.$formatters.unshift(requiredValidator);

attr.$observe('required', function() {
requiredValidator(ngModelCtrl.$viewValue);
});
}

if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
Expand Down
24 changes: 24 additions & 0 deletions test/ng/directive/selectSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1215,6 +1215,30 @@ describe('select', function() {
});


it('should treat an empty array as invalid when `multiple` attribute used', function() {
createSelect({
'ng-model': 'value',
'ng-options': 'item.name for item in values',
'ng-required': 'required',
'multiple': ''
}, true);

scope.$apply(function() {
scope.value = [];
scope.values = [{name: 'A', id: 1}, {name: 'B', id: 2}];
scope.required = true;
});
expect(element).toBeInvalid();

scope.$apply(function() {
// ngModelWatch does not set objectEquality flag
// array must be replaced in order to trigger $formatters
scope.value = [scope.values[0]];
});
expect(element).toBeValid();
});


it('should allow falsy values as values', function() {
createSelect({
'ng-model': 'value',
Expand Down

0 comments on commit 5c97731

Please sign in to comment.