How to restrict input number to non-decimal

独自空忆成欢 提交于 2019-12-24 12:57:19

问题


I have a number input on a page, and I want it restricted to whole number values, no decimals. I am using forms and angularjs for validation. What do I have to do to make decimals not allowed? I tried setting step to 1, but this changed nothing. Many other issues discuss getting browsers to support decimals - I seem to be having the opposite problem.


回答1:


You can make a custom directive for that, incorporating the ngModelController. Like this: Proof of Concept

    module.directive("noDecimalInput", function() {
    return {
        restrict: "A",
        require:"ngModel",
        link: function(scope,element,attr,ctrl) {
            ctrl.$parsers.push(function(value){
                if(value.indexOf(".")>-1) {
                    ctrl.$setValidity("notDecimal",false);
                    return undefined;
                }
                ctrl.$setValidity("notDecimal",true);
                return value;
            });
        }
    }
});


来源:https://stackoverflow.com/questions/27042346/how-to-restrict-input-number-to-non-decimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!