1

I have a text box. I want to restrict user to only copy paste numeric.I dont want copy paste of alphabets and special characters. I have tried below code with out success.

    <!DOCTYPE html>
    <html ng-app="plnk">

      <head>
        <script data-require="angular.js@*" data-semver="2.0.0" src="https://ajax.googleapis`enter code here`.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js"></script>
        <script src="app.js"></script>
      </head>

      <body>
        <h1>Disable copy paste</h1>
       for testing if angular is working {{1+1}}

       <br/>
        <input stopcopypaste ng-model="val" />
      </body>

    </html>   

javascript :

var app = angular.module('plnk', []);
app.controller('MainCtrl', function($scope, $timeout) {
  $scope.val = '1';
});

app.directive('stopcopypaste', function(){
        return {
        scope: {},
        link:function(scope,element){
            element.on('cut copy paste', function (event) {
           key = event.keyCode || event.which;
           if ((47 < key) && (key < 58) || key == 8 || key == 189 || key == 109) {
          return true;
      } else {
              event.preventDefault();
              return false;
      }
        })
            })
        }
    };
});

I cannot restrict the alphabets and special characters with this code.

https://plnkr.co/edit/QGUuNyVqEj7jZtWmlAez?p=preview

pankaj
  • 1,030
  • 5
  • 19
  • 41

1 Answers1

1

You can do it using ng-paste directive and attaching a controller function to it like so:

app.js -

app.controller('MainCtrl', function($scope, $timeout) {
    $scope.val = '1';

    $scope.pasteOptions = function(e) {
        var regex = /^\d+$/;
        var pastedData = e.clipboardData.getData('text/plain');
        if(pastedData.match(regex) === null) {
            e.preventDefault();
            return false;
        }
    };
});

HTML -

<body ng-controller="MainCtrl">
...
...
<input ng-paste="pasteOptions($event)" ng-model="val" />

For copy, cut - ng-copy, ng-cut

Updated plunker - https://plnkr.co/edit/pGk16GUGu9Tc0vTMvQND?p=preview

Aks1357
  • 1,062
  • 1
  • 9
  • 19
  • Your plunk is corect.. But i have a restriction in using ng-paste.. Is it possible to achieve this using custom directive rather than calling a method on ng-paste – pankaj Oct 17 '16 at 19:31
  • What kind of restriction...? you can write custom directive and use jQuery - http://stackoverflow.com/questions/686995/catch-paste-input – Aks1357 Oct 18 '16 at 10:39