Nikita TSB
Nikita TSB

Reputation: 460

Check pasted text in input/textarea for non valid charters

I have input field that i need to check for non valid charters. I use jQuery .on('keyup keypress') function that block all non valid symbols, but when somebody use CTRL+V - all symbols are pasted:(

1234567890zxcvbnmasdfghjklqwertyuiopABCDEFGHIJKLMNOPQRSTUVWXYZ"\'- №&

String with charters are allowed. How to check with .onclick()/bind('paste') if some charters are not allowed.

Thx.

Upvotes: 0

Views: 106

Answers (2)

Marcel Kohls
Marcel Kohls

Reputation: 1857

A suggestion is to sanitize the content on paste, for example:

<input type="text" id="the-input" onkeydown="return yourFunctioToGetKeyDown(event)">

And a sanitize event:

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

});

Take a look on the sample https://jsfiddle.net/MarcelKohls/Lg3a9opo/

Upvotes: 1

B&#225;lint
B&#225;lint

Reputation: 4039

You can use the /[A-Za-z0-9\"\\\'-№&/g to match any non-wanted characters, replace them with nothing, and check if the string is empty.

Note: I'm not sure if there's a contain method for strings, I need to check.

Upvotes: 2

Related Questions