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

Commit 459daca

Browse files
committed
fix(ngModel): validate pattern against the viewValue
Since the HTML5 pattern validation constraint validates the input value, we should also validate against the viewValue. This allows e.g. input[date] to validate both the input format of the date and the date object itself. Fixes #12344
1 parent 01dd588 commit 459daca

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/ng/directive/validators.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,9 @@ var patternDirective = function() {
4343
ctrl.$validate();
4444
});
4545

46-
ctrl.$validators.pattern = function(value) {
47-
return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
46+
ctrl.$validators.pattern = function(modelValue, viewValue) {
47+
// HTML5 pattern constraint validates the input value, so we validate the viewValue
48+
return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
4849
};
4950
}
5051
};

test/ng/directive/validatorsSpec.js

+15
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,21 @@ describe('validators', function() {
204204
expect($rootScope.form.test.$error.pattern).toBe(true);
205205
expect(inputElm).not.toBeValid();
206206
});
207+
208+
209+
it('should validate the viewValue and not the modelValue', function() {
210+
var inputElm = helper.compileInput('<input type="text" name="test" ng-model="value" pattern="\\d{4}$">');
211+
var ctrl = inputElm.controller('ngModel');
212+
213+
ctrl.$parsers.push(function(value) {
214+
return (value * 10) + '';
215+
});
216+
217+
helper.changeInputValueTo('1234');
218+
expect($rootScope.form.test.$error.pattern).not.toBe(true);
219+
expect($rootScope.form.test.$modelValue).toBe('12340');
220+
expect(inputElm).toBeValid();
221+
});
207222
});
208223

209224

0 commit comments

Comments
 (0)