How do I restrict an input to only accept numbers?

前端 未结 17 1223
感情败类
感情败类 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条回答
  • 2020-12-07 10:06

    Easy way, use type="number" if it works for your use case:

    <input type="number" ng-model="myText" name="inputName">
    

    Another easy way: ng-pattern can also be used to define a regex that will limit what is allowed in the field. See also the "cookbook" page about forms.

    Hackish? way, $watch the ng-model in your controller:

    <input type="text"  ng-model="myText" name="inputName">
    

    Controller:

    $scope.$watch('myText', function() {
       // put numbersOnly() logic here, e.g.:
       if ($scope.myText  ... regex to look for ... ) {
          // strip out the non-numbers
       }
    })
    

    Best way, use a $parser in a directive. I'm not going to repeat the already good answer provided by @pkozlowski.opensource, so here's the link: https://stackoverflow.com/a/14425022/215945

    All of the above solutions involve using ng-model, which make finding this unnecessary.

    Using ng-change will cause problems. See AngularJS - reset of $scope.value doesn't change value in template (random behavior)

    0 讨论(0)
  • 2020-12-07 10:07

    Here is a pretty good solution to makes only allow enter number to the input:

    <input type="text" ng-model="myText" name="inputName" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
    
    0 讨论(0)
  • 2020-12-07 10:10

    There are a few ways to do this.

    You could use type="number":

    <input type="number" />
    

    Alternatively - I created a reuseable directive for this that uses a regular expression.

    Html

    <div ng-app="myawesomeapp">
        test: <input restrict-input="^[0-9-]*$" maxlength="20" type="text" class="test" />
    </div>
    

    Javascript

    ;(function(){
        var app = angular.module('myawesomeapp',[])
        .directive('restrictInput', [function(){
    
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    var ele = element[0];
                    var regex = RegExp(attrs.restrictInput);
                    var value = ele.value;
    
                    ele.addEventListener('keyup',function(e){
                        if (regex.test(ele.value)){
                            value = ele.value;
                        }else{
                            ele.value = value;
                        }
                    });
                }
            };
        }]);    
    }());
    
    0 讨论(0)
  • 2020-12-07 10:11

    Try this,

    <input ng-keypress="validation($event)">
    
     function validation(event) {
        var theEvent = event || window.event;
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode(key);
        var regex = /[0-9]|\./;
        if (!regex.test(key)) {
            theEvent.returnValue = false;
            if (theEvent.preventDefault) theEvent.preventDefault();
        }
    
    }
    
    0 讨论(0)
  • 2020-12-07 10:12
       <input type="text" name="profileChildCount" id="profileChildCount" ng-model="profile.ChildCount" numeric-only maxlength="1" />
    

    you can use numeric-only attribute .

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题