You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Fixesangular#12344
BREAKING CHANGE:
`ngPattern` and `pattern` directives will validate the regex against
the `viewValue` of `ngModel`, i.e. the value of the model before the
$parsers are applied. Previously, the modelValue (the result of the
$parsers) was validated.
This fixes issues where `input[date]` and
`input[number]` could not be validated because the viewValue string
had been parsed into `Date`/`Number` respectively. This change also
brings the directives in line with HTML5 constraint validation,
which validates against the value of the input.
The change is unlikely to cause applications to fail, because even
before Angular 1.3, the value that was validated by pattern could have
been manipulated by the $parsers array, as all validation was done
inside this pipeline.
If you rely on the pattern being validated against the modelValue,
you must create your own validator directive that overwrites
the built-in pattern validator:
```
.directive('patternModelOverwrite', function patternModelOverwriteDirective() {
return {
restrict: 'A',
require: '?ngModel',
priority: 1,
compile: function() {
var regexp, patternExp;
return {
pre: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.$observe('pattern', function(regex) {
//The built-in directive will call our overwritten validator (see below).
//We just need to update the regex. The preLink fn guaranetees our observer
//is called first
if (isString(regex) && regex.length > 0) {
regex = new RegExp('^' + regex + '$');
}
if (regex && !regex.test) {
//The built-in validator will throw at this point
return;
}
regexp = regex || undefined;
});
},
post: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
regexp, patternExp = attr.ngPattern || attr.pattern;
//The postLink fn guarantees we overwrite the built-in pattern validator
ctrl.$validators.pattern = function(value) {
return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
};
}
};
}
};
});
```
0 commit comments