SD Dev
SD Dev

Reputation: 345

Only accepting numbers in an input field. The angular way (without html5)

I have a field that should only accept numbers, I know normally we do input type="number". What's the best way in angular to allow only numbers?

Upvotes: 0

Views: 63

Answers (2)

Nishi Bangar
Nishi Bangar

Reputation: 948

Probably you can make use of this simple directive..

 // ---Directive for Digit restriction on input fields.---------

myApp.directive('numbersOnly', function() {
return {
    require : 'ngModel',
    link : function(scope, element, attrs, modelCtrl) {
        modelCtrl.$parsers.push(function(inputValue) {
            // if the input is 'undefined'
            if (inputValue == undefined)
                return ''
            var transformedInput = inputValue.replace(/[^0-9]/g, '');
            if (transformedInput != inputValue) {
                modelCtrl.$setViewValue(transformedInput);
                modelCtrl.$render();
            }

            return transformedInput;
        });
    }
};

});

and in HTML , you can declare the directive as

<input type="numbers" numbers-only  ng-model="numberModel">

So, ideally, this input field will update your model with numbers as the only data..

What is happening here is , each time a character is pressed, it is being monitored by our directive, numbersOnly, and here is where you pick out only numbers as your input.

Hope this helps out... Cheers

Upvotes: 0

ciril sebastian
ciril sebastian

Reputation: 549

you can create a directive similar given below and then use it in the HTML element as an attribute

.directive('validNumber', function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            link: function (scope, element, attrs, ngModelCtrl) {

                //8:"BACKSPACE",9:"TAB",17:"CTRL",18:"ALT",37:"LEFT",
                //38:"UP",39:"RIGHT",40:"DOWN",45:"INSERT",46:"DELETE",
                //48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9", 67:"C",86:"V",
                //96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9",
                //109:"-",110:".",144:"NUMLOCK", 189:"-",190:".",

                var keyCode = [8, 9, 17, 37, 38, 39, 40, 45, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 67, 86, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 109, 110, 144, 189, 190];
                element.bind("keydown", function (event) {
                    if ($.inArray(event.which, keyCode) == -1) {
                        scope.$apply(function () {
                            scope.$eval(attrs.validNumber);
                            event.preventDefault();
                        });
                        event.preventDefault();
                    }

                });
            }
        };
    });

Upvotes: 1

Related Questions