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

fix(required): false is a valid model value for required <select> #3658

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
5 changes: 3 additions & 2 deletions src/ng/directive/input.js
Original file line number Diff line number Diff line change
Expand Up @@ -1228,14 +1228,15 @@ var requiredDirective = function() {
attr.required = true; // force truthy in case we are on non input element

var validator = function(value) {
if (attr.required && (isEmpty(value) || value === false)) {
if (attr.required && (isEmpty(value) || !acceptFalse && value === false)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Why this condition ? why is false invalid for inputs ?

ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
},
acceptFalse = nodeName_(elm).toLowerCase() !== 'input' || attr.type !== 'checkbox';

ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
Expand Down
20 changes: 19 additions & 1 deletion test/ng/directive/inputSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1093,7 +1093,25 @@ describe('input', function() {
compileInput('<input type="text" ng-model="notDefiend" required />');
scope.$digest();
expect(inputElm).toBeInvalid();
})
});

it('should allow `false` as a valid value when the input type is not "checkbox"', function() {
compileInput('<input type="radio" ng-value="true" ng-model="answer" required />' +
'<input type="radio" ng-value="false" ng-model="answer" required />');

scope.$apply();
expect(inputElm).toBeInvalid();

scope.$apply(function() {
scope.answer = true;
});
expect(inputElm).toBeValid();

scope.$apply(function() {
scope.answer = false;
});
expect(inputElm).toBeValid();
});
});


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 @@ -1198,6 +1198,30 @@ describe('select', function() {
});
expect(element).toBeValid();
});

it('should allow falsy values as values', function() {
createSelect({
'ng-model': 'value',
'ng-options': 'item.value as item.name for item in values',
'ng-required': 'required'
}, true);

scope.$apply(function() {
scope.values = [{name: 'True', value: true}, {name: 'False', value: false}];
scope.required = false;
});

element.val('1');
browserTrigger(element, 'change');
expect(element).toBeValid();
expect(scope.value).toBe(false);

scope.$apply(function() {
scope.required = true;
});
expect(element).toBeValid();
expect(scope.value).toBe(false);
});
});
});

Expand Down