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

fix(select): ngRequired invalidate when modelValue is empty array #5337

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this little jig be turned into a separate bug? Perhaps ngModelController could compare value.length to the old length (and try not to break in the case of scalars, of course) --- to avert this somewhat. Or perhaps just use the objectEquality flag?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should open a new bug for that. See #5449

scope.value = [scope.values[0]];
});
expect(element).toBeValid();
});


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