benjamin54
benjamin54

Reputation: 1300

Prevent user from typing non-number input

I need to allow user to type in numbers only. Here is what I did.

Portion of my directive template:

<input type="text" maxlength="5" ng-keypress="allowNumbers($event)">

Function in my directive:

$scope.allowNumbers= function (ev) {
    var key = ev.charCode || ev.keyCode || 0;
    var allowed = (
        key == 8 ||
        key == 9 ||
        key == 13 ||
        key == 46 ||
        key == 110 ||
        key == 190 ||
        (key >= 35 && key <= 40) ||
        (key >= 48 && key <= 57) ||
        (key >= 96 && key <= 105));

    return allowed;
};

While debugging, I noticed that even the function returns true or false, the value in textbox does get entered. Can I somehow prevent it for non-number key press?

Upvotes: 0

Views: 2135

Answers (3)

Erazihel
Erazihel

Reputation: 7615

You can use a directive:

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

                return transformedInput;
            });
        }
    };
});

And use it like this:

<input type="text" maxlength="5" numbers-only/>

You could use this behavior into any input needed just by adding the numbers-only attribute.

See working JSFiddle.

Upvotes: 4

Hassan Tariq
Hassan Tariq

Reputation: 740

    function IsNumeric(e) {

var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
//  document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}

and In html

     <input type="text"  onkeypress="return IsNumeric(event);" />

Upvotes: 3

deceze
deceze

Reputation: 522626

I'd approach this simpler and in a way that is guaranteed to catch more possible forms of input (e.g. copy-paste):

<input type="number" ng-model="myNumber">

$scope.$watch('myNumber', function (input) {
    $scope.myNumber = input.replace(/\D/g, '');
});

Upvotes: 3

Related Questions