Skip to content

Commit

Permalink
fix(required): false is a valid model value when not a checkbox
Browse files Browse the repository at this point in the history
Make the `required` directive accept the model value `false` when it is
not an <input> element or when the <input> element is not a checkbox

Closes angular#3490 angular#2594
  • Loading branch information
lgalfaso committed Sep 24, 2013
1 parent d307242 commit 2575b57
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
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)) {
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

0 comments on commit 2575b57

Please sign in to comment.