Skip to content

Commit

Permalink
fix(input): use ValidityState to determine validity
Browse files Browse the repository at this point in the history
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
  • Loading branch information
caitp committed Jan 23, 2014
1 parent e020916 commit 5b804a6
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/ng/directive/input.js
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,28 @@ function validate(ctrl, validatorName, validity, value){
return validity ? value : undefined;
}


function validateHtml5(ctrl, validatorName, element) {
var v = element.prop('validity');
if (v && isObject(v)) {
var validator = function(value) {
// Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can
// perform the required validation)
if (!ctrl.$error[validatorName] && (v.badInput || v.customError || v.typeMismatch) &&
!v.valueMissing) {
ctrl.$setValidity(validatorName, false);
return undefined;
}
return value;
};
ctrl.$parsers.push(validator);
ctrl.$formatters.push(validator);
}
}

function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var validity = element.prop('validity');
validity = isObject(validity) && validity;
// In composition mode, users are still inputing intermediate text buffer,
// hold the listener until composition is done.
// More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
Expand All @@ -431,7 +452,7 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
value = trim(value);
}

if (ctrl.$viewValue !== value) {
if (ctrl.$viewValue !== value || (validity && !value && !validity.valueMissing)) {
if (scope.$$phase) {
ctrl.$setViewValue(value);
} else {
Expand Down Expand Up @@ -551,6 +572,8 @@ function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
}
});

validateHtml5(ctrl, 'number', element);

ctrl.$formatters.push(function(value) {
return ctrl.$isEmpty(value) ? '' : '' + value;
});
Expand Down

0 comments on commit 5b804a6

Please sign in to comment.