JeAr JeAr - 7 months ago 18
HTML Question

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,

Answer

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);
       });

    });
});