James Dev J James Dev J - 1 month ago 11
AngularJS Question

How to prevent pasting of non-numerical values in textbox?



app.directive('allowPattern', [allowPatternDirective]);
function allowPatternDirective() {
return {
restrict: "A",
compile: function (tElement, tAttrs) {
return function (scope, element, attrs) {
element.bind("keypress", function (event) {
var keyCode = event.which || event.keyCode;
if ((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122)) {
event.preventDefault();
return false;
}
});

};
}
};
}

<input type="text" allow-pattern="[0-9]" autofocus />





How to prevent pasting in textbox when the Pasted content is not applicable for that field? (It should paste for applicable conten )

Application Background: C#, AngularJS

I have a textbox in my application which should accept numbers only. Currently I am using a directive for Keypress which prevents entering the non-numeric values. But when I copy-paste the non-numeric values along with numeric values(Ex: NUMBER123), it is getting pasted. But the requirement is it should not paste at all. How can I achieve this through appropriate angular js directives/ jquery.

Answer

Here is your requirement.

var app = angular.module('app', []);

app.directive('allowNumbers', function() {
  return {
    require: 'ngModel',
    link: function (scope, element, attr, ngModelCtrl) {
      function test(text) {
        var input = text.replace(/[^0-9]/g, '');
        if(input !== text) {
            ngModelCtrl.$setViewValue("");
            ngModelCtrl.$render();
        }
        return input;
      }
      ngModelCtrl.$parsers.push(test);
    }
  }; 
});

app.controller('MainCtrl', function($scope) {
});
<html ng-app="app">
  
  <head lang="en">
    <meta charset="utf-8">
    <title>Directive</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script src="app.js"></script>
  </head>
  
  <body ng-controller="MainCtrl">
    <input allow-numbers type="text" ng-model="test" autofocus>
  </body>

</html>

Please run this snippet

Js fiddle of the directive

Comments