Skip to content

Commit b80808a

Browse files
committed
fix(input): format as string before running minlength/maxlength formatters
Previously, minlength/maxlength would not work correctly when dealing with non-string model values. A better fix for this has already been implemented in 1.3, but unfortunately implementing that fix in 1.2 is a bit harder as it requires a number of commits to be backported in order to solve the problem correctly. Closes angular#5936
1 parent 37f2265 commit b80808a

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/ng/directive/input.js

+2
Original file line numberDiff line numberDiff line change
@@ -608,6 +608,7 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
608608
if (attr.ngMinlength) {
609609
var minlength = int(attr.ngMinlength);
610610
var minLengthValidator = function(value) {
611+
if (typeof value !== 'string' && !ctrl.$isEmpty(value)) value = value.toString();
611612
return validate(ctrl, 'minlength', ctrl.$isEmpty(value) || value.length >= minlength, value);
612613
};
613614

@@ -619,6 +620,7 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
619620
if (attr.ngMaxlength) {
620621
var maxlength = int(attr.ngMaxlength);
621622
var maxLengthValidator = function(value) {
623+
if (typeof value !== 'string' && !ctrl.$isEmpty(value)) value = value.toString();
622624
return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value);
623625
};
624626

test/ng/directive/inputSpec.js

+28
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,20 @@ describe('input', function() {
789789
changeInputValueTo('aaa');
790790
expect(scope.value).toBe('aaa');
791791
});
792+
793+
794+
it('should convert non-empty non-strings to string before formatting', function() {
795+
compileInput('<input type="text" ng-model="value" name="alias" ng-minlength="3">');
796+
scope.value = 10;
797+
scope.$digest();
798+
799+
expect(scope.form.alias.$error.minlength).toBe(true);
800+
801+
scope.value = 100;
802+
scope.$digest();
803+
804+
expect(scope.form.alias.$error.minlength).not.toBe(true);
805+
});
792806
});
793807

794808

@@ -803,6 +817,20 @@ describe('input', function() {
803817
changeInputValueTo('aaa');
804818
expect(scope.value).toBe('aaa');
805819
});
820+
821+
822+
it('should convert non-empty non-strings to string before formatting', function() {
823+
compileInput('<input type="text" ng-model="value" name="alias" ng-maxlength="3">');
824+
scope.value = 1000;
825+
scope.$digest();
826+
827+
expect(scope.form.alias.$error.maxlength).toBe(true);
828+
829+
scope.value = 100;
830+
scope.$digest();
831+
832+
expect(scope.form.alias.$error.maxlength).not.toBe(true);
833+
});
806834
});
807835

808836

0 commit comments

Comments
 (0)