Fritz-krieg
Fritz-krieg

Reputation: 51

Ng-keypress prevent default for specific charCode

I have an input that is type="number". I want to prevent the user from typing decimals, addition, subtraction, or e into the input. Currently I am trying to e.preventDefault() on ng-keypress to disable the key completely. But it is not working. I am using typescript and angularJs. It is seeing the event on keypress but it is not preventing the entry from being made. Or, would using ng-pattern with a regex be an alternative option retrict input to 0-9?

setCapacityType(e) {
  let keyCode = (e.keyCode ? e.keyCode : e.which);
  
  if (keyCode < 48 && keyCode > 57) {
    e.preventDefault();
    console.log("xx");
  }
}
<input type="number" ng-keydown="vm.setCapacityType($event)"
autocomplete="off" autocorrect="off" spellcheck="false">

Upvotes: 0

Views: 11920

Answers (1)

developer033
developer033

Reputation: 24884

Well, two things:

  1. First, you have to instantiate your function:
vm.setCapacityType = function(e) {
  1. To allows only numbers [0-9] you should write your condition as below:
if (keyCode < 48 || keyCode > 57) {

Now, you can have something like this:

 angular.module('app', [])
   .controller('mainCtrl', function() {
     var vm = this;

     vm.setCapacityType = function(e) {
       let keyCode = (e.keyCode ? e.keyCode : e.which);
       if (keyCode < 48 || keyCode > 57) {
         console.log("Prevent!");
         e.preventDefault();
       }
     }
   });
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl as main">
  <input type="text" ng-keydown="main.setCapacityType($event)" autocomplete="off" autocorrect="off" spellcheck="false">
</body>

</html>

ng-pattern with a regex be an alternative option retrict input to 0-9?

No, ngPattern directive doesn't prevent/restrict the input.

Upvotes: 4

Related Questions