How do I restrict an input to only accept numbers?

前端 未结 17 1245
感情败类
感情败类 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:00

    Here's my implementation of the $parser solution that @Mark Rajcok recommends as the best method. It's essentially @pkozlowski.opensource's excellent $parser for text answer but rewritten to only allow numerics. All credit goes to him, this is just to save you the 5 minutes of reading that answer and then rewriting your own:

    app.directive('numericOnly', function(){
        return {
            require: 'ngModel',
            link: function(scope, element, attrs, modelCtrl) {
    
                modelCtrl.$parsers.push(function (inputValue) {
                    var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
    
                    if (transformedInput!=inputValue) {
                        modelCtrl.$setViewValue(transformedInput);
                        modelCtrl.$render();
                    }
    
                    return transformedInput;
                });
            }
        };
    });
    

    And you'd use it like this:

    
    

    Interestingly, spaces never reach the parser unless surrounded by an alphanumeric, so you'd have to .trim() as needed. Also, this parser does NOT work on . For some reason, non-numerics never make it to the parser where they'd be removed, but they do make it into the input control itself.

提交回复
热议问题