From e0e8a11f3a110bfeee8196a41d316c28a4fb78d9 Mon Sep 17 00:00:00 2001 From: Caitlin Potter Date: Wed, 22 Jan 2014 22:30:20 -0500 Subject: [PATCH] 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 #4293 Closes #2144 Closes #4857 Closes #5120 Closes #4945 Closes #5500 --- src/ng/directive/input.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/ng/directive/input.js b/src/ng/directive/input.js index 53a8ddd4d70a..997a428f5e5b 100644 --- a/src/ng/directive/input.js +++ b/src/ng/directive/input.js @@ -404,6 +404,24 @@ function validate(ctrl, validatorName, validity, value){ return validity ? value : undefined; } + +function validateHtml5(ctrl, validatorName, element) { + var validity = element.prop('validity'); + if (validity && typeof validity === 'object') { + 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] && !validity.valid && !validity.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) { // In composition mode, users are still inputing intermediate text buffer, // hold the listener until composition is done. @@ -551,6 +569,8 @@ function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { } }); + validateHtml5(ctrl, 'number', element); + ctrl.$formatters.push(function(value) { return ctrl.$isEmpty(value) ? '' : '' + value; });