Raj
Raj

Reputation: 204

allow only numeric value to enter in the input field

I have written the below directive which allow only numeric value to be entered in the input field.The same is working fine except allowing alphanumeric also to be entered for example if i have copied "abc123" and pasting the same in input field then it is accepting numeric and ignoring alphabet which should not be the case .In this case it should not allow anything to be paste in the input field. Please help.

function link(scope, element, attrs, modelCtrl){
        modelCtrl.$parsers.push(function(inputValue) {
            if (inputValue === undefined) return '';

            var cleanInputValue = inputValue.replace('.', '')
                .replace(/[^0-9.]/g, '')
                .replace(/\./, "x")
                .replace(/\./g, "")
                .replace(/x/, ".");
            if (cleanInputValue != inputValue) {
                modelCtrl.$setViewValue(cleanInputValue);
                modelCtrl.$render();
            }
            return cleanInputValue;
        })
    }

Upvotes: 2

Views: 1743

Answers (4)

Deepu Reghunath
Deepu Reghunath

Reputation: 9713

This may helpful

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button 
{   
    -webkit-appearance: none;
    margin: 0; /* some part are still there even though it is hidden */
}
<div ng-app="app">
  <input type="number" >
</div>

if you feel uncomfortable with key 'e' use the following one

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.myFunc = function (event) {    
    if (event.keyCode < 48 || event.keyCode > 57)
    {
        event.preventDefault();
    }
};
});
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button 
{   
    -webkit-appearance: none;
    margin: 0; /* some part are still there even though it is hidden */
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <input type="text" ng-keypress="myFunc($event)">
</div>

Upvotes: 1

Red
Red

Reputation: 7334

Below is a simple directive, which allows you only to enter numbers inside a input field.

When linked to an input field:

<input type="text" ng-model="test" valid-number>

It bind a keydown event on the input field, which checks what key has been pressed. Each key on your keyboard has an global number. For example: enter has the numer 13 assigned.

A complete list of key codes

When you press a key on your keyboard, and its matches the key code listed inside var keyCode

var keyCode = [8, 9, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110];

then we prevent the action from executing.

(function () {

  angular.module("app", [])
  
  .directive("validNumber", function () {
        return {
            restrict: "EA",
            require: "?ngModel",
            link: function (scope, element, attrs, ngModel) {
                if (!ngModel) return;
                var keyCode = [8, 9, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110];
                element.bind("keydown", function (event) {
                    if ($.inArray(event.which, keyCode) === -1) {
                        scope.$apply(function () {
                            scope.$eval(attrs.validNumber);
                            event.preventDefault();
                        });
                        event.preventDefault();
                    }
                });
            }
        };
    });

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="app">
  <input type="text" ng-model="test" valid-number="" name="test">
</div>


UPDATE


Based on your comments on other posted awnsers. You can just use .replace() function to replace everything except numbers.

Even when you copy and paste a valid number with invalid characters, it will replace the invalid characters.

I allowed users to write an dot ., because 5.2 is a valid number. But if you dont want this, you can replace the regex with

value.replace(/[^0-9]/g, "");

DEMO

(function () {

  angular.module("app", [])
  
  .directive("validNumber", function () {
        return {
            restrict: "EA",
            require: "?ngModel",
            link: function (scope, element, attrs, ngModel) {
                if (!ngModel) return;

                element.bind("keypress keyup", function (event) {
                    var value = element.val();
                    value = value.replace(/[^0-9.]/g, "");
                    
                    element.val(value);
                });
            }
        };
    });

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="app">
  <input type="text" ng-model="test" valid-number="" name="test">
</div>

Upvotes: 1

Maxim Shoustin
Maxim Shoustin

Reputation: 77930

$parsers:

<input type="text" ng-model="test" format="number" />

JS

app.directive('format', ['$filter', '$window', function($filter, $window) {
  return {
    require: '?ngModel',
    link: function(scope, elem, attrs, ctrl) {
      if (!ctrl) return;

      scope.vKey = 86;
      scope.ctrlVDown = false;
      angular.element($window).bind("keydown", function($event) {
        console.log($event.keyCode);
        if ($event.keyCode == scope.vKey) {
          scope.ctrlVDown = true;
        } else {
          scope.ctrlVDown = false;
        }
      });


      ctrl.$parsers.unshift(function(viewValue) {
        var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');

        console.log(scope.ctrlVDown);

        if (scope.ctrlVDown && plainNumber.length !== viewValue.length) {
          elem.val('');
          return '';
        } else {
          elem.val(plainNumber);
          return plainNumber;
        }
      });
    }
  };
}]);

Demo Fiddle

Upvotes: 1

Danny K
Danny K

Reputation: 34

Did you try to set your input type to number?

<input type="number" />

This will automatically strip all alphabetical characters even when user will use paste

Upvotes: 0

Related Questions