Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable special characters from paste in a textbox

How to disable special characters from paste in a textbox?

Im using a onkeypress event handler

function disableOtherChar(evt) {
    var charCode;
    charCode = (evt.which) ? evt.which : evt.keyCode;
    var ctrl;
    ctrl = (document.all) ? event.ctrlKey : evt.modifiers & Event.CONTROL_MASK;
    if ((charCode > 47 && charCode < 58) || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8 || charCode == 9 || charCode == 45 || (ctrl && charCode == 86) || ctrl && charCode == 67) {
        return true;
    } else {
        $(":text").live("cut copy paste", function (e) {
            e.preventDefault();
        });
        return false;
    }
}

But it doesnt block special characters when pasting, only in entering,

like image 347
JeAr Avatar asked May 28 '13 01:05

JeAr


2 Answers

suppose that you have a Input

 <input id="textInput" name="textInput">

and you have the following script to validate the copy:

$(function(){

   $( "#textInput" ).bind( 'paste',function()
   {
       setTimeout(function()
       { 
          //get the value of the input text
          var data= $( '#textInput' ).val() ;
          //replace the special characters to '' 
          var dataFull = data.replace(/[^\w\s]/gi, '');
          //set the new value of the input text without special characters
          $( '#textInput' ).val(dataFull);
       });

    });
});
like image 140
Cristian Avatar answered Sep 30 '22 09:09

Cristian


You could use a 3rd party plugin like jquery.alphanum, it works for paste (ctrl+v) too. The code looks like this :

$("input").alphanum();

Or you could use it in a more spceficied way like this :

$("#elemet").alphanum({
    allow      : "asd",
    disallow   : "!@#",
    allowUpper : false
});

The above code you need to add it into your JQuery declaration.

I mention the fact that you can also modify the blacklist array from the script jquery.alphanum.js on line 124. You will find a function name getBlacklistAscii, in that you modify var blacklist = ... to what suits you.

like image 36
Philipos D. Avatar answered Sep 30 '22 10:09

Philipos D.