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

Commit 9be1198

Browse files
committed
fix(required): correctly validate when required on non-input element is surrounded by ngIf
Closes #16830
1 parent 005dd97 commit 9be1198

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/ng/directive/validators.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,15 +68,21 @@ var requiredDirective = ['$parse', function($parse) {
6868
require: '?ngModel',
6969
link: function(scope, elm, attr, ctrl) {
7070
if (!ctrl) return;
71-
var value = attr.required || $parse(attr.ngRequired)(scope);
71+
// For boolean attributes like required, presence means true
72+
var value = 'required' in attr || $parse(attr.ngRequired)(scope);
7273

73-
attr.required = true; // force truthy in case we are on non input element
74+
if (!attr.ngRequired) {
75+
// force truthy in case we are on non input element
76+
// (input elements do this automatically for boolean attributes like required)
77+
attr.required = true;
78+
}
7479

7580
ctrl.$validators.required = function(modelValue, viewValue) {
7681
return !value || !ctrl.$isEmpty(viewValue);
7782
};
7883

7984
attr.$observe('required', function(newVal) {
85+
8086
if (value !== newVal) {
8187
value = newVal;
8288
ctrl.$validate();

test/ng/directive/validatorsSpec.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -731,6 +731,7 @@ describe('validators', function() {
731731
expect(helper.validationCounter.required).toBe(1);
732732
});
733733

734+
734735
it('should validate once when inside ngRepeat, and set the "required" error when ngRequired is false by default', function() {
735736
$rootScope.isRequired = false;
736737
$rootScope.refs = {};
@@ -744,5 +745,15 @@ describe('validators', function() {
744745
expect($rootScope.refs.input.$error.required).toBeUndefined();
745746
});
746747

748+
749+
it('should validate only once when inside ngIf with required on non-input elements', inject(function($compile) {
750+
$rootScope.value = '12';
751+
$rootScope.refs = {};
752+
helper.compileInput('<div ng-if="true"><span ng-model="value" ng-ref="refs.ctrl" ng-ref-read="ngModel" required validation-spy="required"></span></div>');
753+
$rootScope.$digest();
754+
755+
expect(helper.validationCounter.required).toBe(1);
756+
expect($rootScope.refs.ctrl.$error.required).not.toBe(true);
757+
}));
747758
});
748759
});

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy