简体   繁体   中英

Internet Explorer, ng-pattern and input type “number” in form validation

In a web application that we are building, we came across some weird bug that only happens with Internet Explorer.

The input validation as seen in this plunker works fine in all browsers except in IE (we have to support IE10+). We use type="number" in our inputs that expect numbers since it makes it so easy in most browsers to make sure that the user only enters allowed characters. We also use ng-pattern="/^\\d+$/" to add some more validation over the type of numbers allowed, plus it is the only validation we have in IE since the input type is not supported.

The problem is: input validation almost works as expected, except when we enter letters as the first characters of our input ("abb45" for example). It does not even think that it is an invalid input! I saw in another SO thread that putting required on the input would trigger the validation properly, but in our case, this particular field is not mandatory at all. Plus, even if the field is marked invalid, the validation message is not shown (I'm not sure where the validation error comes from in that case).

Removing the type="number" is a workaround (it does solve the problem in IE), but we would rather try to find another solution before making this change that would break the "smoothness" of numeric inputs in other browsers.

Note: we do not use jQuery (only jQuery lite since angular has it as a depency).

Yes IE has issue with type="number" . I would encourage you too use directive to accept only numbers

angular.module('moduleName').directive('numbersOnly', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModelCtrl) {
            function fromUser(text) {
                if (text) {
                    var transformedInput = text.replace(/[^-0-9\.]/g, '');

                    if (transformedInput !== text) {
                        ngModelCtrl.$setViewValue(transformedInput);
                        ngModelCtrl.$render();
                    }
                    return transformedInput;
                }
                return undefined;
            }            
            ngModelCtrl.$parsers.push(fromUser);
        }
    };
});

, In html add number-only attribute to

Ex: <input number-only />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM