How do I restrict an input to only accept numbers?

前端 未结 17 1248
感情败类
感情败类 2020-12-07 09:28

I am using ngChange in AngularJS to trigger a custom function that will remove any letters the user adds to the input.



        
17条回答
  •  猫巷女王i
    2020-12-07 10:12

    DECIMAL

    directive('decimal', function() {
                    return {
                        require: 'ngModel',
                        restrict: 'A',
                        link: function(scope, element, attr, ctrl) {
                            function inputValue(val) {
                                if (val) {
                                    var digits = val.replace(/[^0-9.]/g, '');
    
                                    if (digits.split('.').length > 2) {
                                        digits = digits.substring(0, digits.length - 1);
                                    }
    
                                    if (digits !== val) {
                                        ctrl.$setViewValue(digits);
                                        ctrl.$render();
                                    }
                                    return parseFloat(digits);
                                }
                                return "";
                            }
                            ctrl.$parsers.push(inputValue);
                        }
                    };
                });
    

    DIGITS

    directive('entero', function() {
                return {
                    require: 'ngModel',
                    restrict: 'A',
                    link: function(scope, element, attr, ctrl) {
                        function inputValue(val) {
                            if (val) {
                                var value = val + ''; //convert to string
                                var digits = value.replace(/[^0-9]/g, '');
    
                                if (digits !== value) {
                                    ctrl.$setViewValue(digits);
                                    ctrl.$render();
                                }
                                return parseInt(digits);
                            }
                            return "";
                        }
                        ctrl.$parsers.push(inputValue);
                    }
                };
            });
    

    angular directives for validate numbers

提交回复
热议问题