Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 5c97731

Browse files
Caitlin Potterpetebacondarwin
Caitlin Potter
authored andcommitted
fix(select): invalidate when 'multiple, required and model is []`
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 #5337
1 parent b2e472e commit 5c97731

File tree

2 files changed

+27
-11
lines changed

2 files changed

+27
-11
lines changed

src/ng/directive/select.js

+3-11
Original file line numberDiff line numberDiff line change
@@ -221,18 +221,10 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
221221
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
222222

223223
// required validator
224-
if (multiple && (attr.required || attr.ngRequired)) {
225-
var requiredValidator = function(value) {
226-
ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
227-
return value;
224+
if (multiple) {
225+
ngModelCtrl.$isEmpty = function(value) {
226+
return !value || value.length === 0;
228227
};
229-
230-
ngModelCtrl.$parsers.push(requiredValidator);
231-
ngModelCtrl.$formatters.unshift(requiredValidator);
232-
233-
attr.$observe('required', function() {
234-
requiredValidator(ngModelCtrl.$viewValue);
235-
});
236228
}
237229

238230
if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);

test/ng/directive/selectSpec.js

+24
Original file line numberDiff line numberDiff line change
@@ -1215,6 +1215,30 @@ describe('select', function() {
12151215
});
12161216

12171217

1218+
it('should treat an empty array as invalid when `multiple` attribute used', function() {
1219+
createSelect({
1220+
'ng-model': 'value',
1221+
'ng-options': 'item.name for item in values',
1222+
'ng-required': 'required',
1223+
'multiple': ''
1224+
}, true);
1225+
1226+
scope.$apply(function() {
1227+
scope.value = [];
1228+
scope.values = [{name: 'A', id: 1}, {name: 'B', id: 2}];
1229+
scope.required = true;
1230+
});
1231+
expect(element).toBeInvalid();
1232+
1233+
scope.$apply(function() {
1234+
// ngModelWatch does not set objectEquality flag
1235+
// array must be replaced in order to trigger $formatters
1236+
scope.value = [scope.values[0]];
1237+
});
1238+
expect(element).toBeValid();
1239+
});
1240+
1241+
12181242
it('should allow falsy values as values', function() {
12191243
createSelect({
12201244
'ng-model': 'value',

0 commit comments

Comments
 (0)