James Dev J James Dev J - 3 years ago 163
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)) {
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 Source

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) {
        return input;

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


Please run this snippet

Js fiddle of the directive

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download