Skip to content

Commit 4030c95

Browse files
committed
fix(input): use ValidityState to determine validity
In browsers where HTML5 constraint validation is (partially) implemented, an invalid number entered into an input[type=number] (for example) input element would be visible to the script context as the empty string. When the required or ngRequired attributes are not used, this results in the invalid state of the input being ignored and considered valid. To address this, a validator which considers the state of the HTML5 ValidityState object is used when available. Closes angular#4293 Closes angular#2144 Closes angular#4857 Closes angular#5120 Closes angular#4945 Closes angular#5500
1 parent e020916 commit 4030c95

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/ng/directive/input.js

+21
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,25 @@ function validate(ctrl, validatorName, validity, value){
404404
return validity ? value : undefined;
405405
}
406406

407+
408+
function validateHtml5(ctrl, validatorName, element) {
409+
var v = element.prop('validity');
410+
if (v && typeof v === 'object') {
411+
var validator = function(value) {
412+
// Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can
413+
// perform the required validation)
414+
if (!ctrl.$error[validatorName] && (v.badInput || v.customError || v.typeMismatch) &&
415+
!v.valueMissing) {
416+
ctrl.$setValidity(validatorName, false);
417+
return undefined;
418+
}
419+
return value;
420+
};
421+
ctrl.$parsers.push(validator);
422+
ctrl.$formatters.push(validator);
423+
}
424+
}
425+
407426
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
408427
// In composition mode, users are still inputing intermediate text buffer,
409428
// hold the listener until composition is done.
@@ -551,6 +570,8 @@ function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
551570
}
552571
});
553572

573+
validateHtml5(ctrl, 'number', element);
574+
554575
ctrl.$formatters.push(function(value) {
555576
return ctrl.$isEmpty(value) ? '' : '' + value;
556577
});

0 commit comments

Comments
 (0)