5

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,

Eduardo M
  • 1,007
  • 11
  • 17
JeAr
  • 107
  • 1
  • 2
  • 7

4 Answers4

13

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

    });
});
Cristian
  • 1,480
  • 5
  • 32
  • 65
1

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.

Philipos D.
  • 2,036
  • 1
  • 26
  • 33
0

Not an answer, just a comment regarding:

var ctrl;
ctrl = (document.all) ? event.ctrlKey:evt.modifiers & Event.CONTROL_MASK;

Please learn to use feature detection, inferring behaviour based on object inference is doomed to fail at least some of the time.

Also, don't use the key code, test the actual characters. E.g if you just want to allow letters, numbers and few others:

function hasInvalidChars(s) {

  // allow letters, spaces, numbers only
  var validChars = /[\w\s\d]/gi;
  var x = s.replace(validChars, '');
  return !!x.length;
}

alert(hasInvalidChars('asdf1234 1234asd'));  // false
alert(hasInvalidChars('asdf1.234 1234asd')); // true

Expand the set of valid characters to whatever you want.

Oh, if you want it as a one–liner:

function hasInvalidChars(s) {
  return !!s.replace(/[\w\s\d]/gi, '').length;
}
RobG
  • 142,382
  • 31
  • 172
  • 209
0

I have changed a bit the script provided by Christian.

This version replaces everything that is not between spaces (ASCII DEC 32) to tilde (ASCII DEC 126) and whitespace characters. Meaning all characters that are not-visible should be removed.

If you add the class api_clean_characters in a Jquery environment this should work out of the box.

<textarea class="api_clean_characters"></textarea>


$(function(){

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

    });
});
Tk421
  • 6,196
  • 6
  • 38
  • 47