0

Very similar to this question, but I don't want to hijack that thread with my specifics.

How to disable special characters from paste in a textbox

I have a form to display a jquery grid and a search textbox above it. I want to prevent our customers from pasting text that contains special characters (like a tab control) because it causes the jquery to hang.

I modified my file to include what looks like the best solution for my scenario:

    $(document).ready(function() {
      $('input').bind('paste', function() {
        setTimeout(function() {
          var obj = ('input').val();
          var text = obj.replace(/\W+/g, ' ');
          $('input').val(text);
        });
      });
    });

The function would go in the $(document).ready section, right?

Does all does data.replace(/[^\w\s]/gi, '') replace? I want to catch \t for sure - possibly others.

My jQuery-fu and regex-fu are not great, so there could be issues with those.

With the script above added, I am still able to paste a simple string like a b into the textbox and cause jquery to hang.

<body>
  <div>The text below has a tab between the <em>a</em> and the <em>b</em>:</div>
    <pre>a  b</pre>
  <div>Modify the regular expression in the javascript to replace the tab with a single space whenever you paste it into the text box below.</div>
  <div><input type="text"></div>
  <div><a href="#">x</a></div>
</body>

https://jsfiddle.net/jp2code/5enmojb2/15/

  • If it's a name field, why not setting a regex rules that allows *only* legit characters than *disallow* unique characters? So only A-Z letters and a single space between. – Ofir Baruch Jan 11 '21 at 20:21
  • check https://stackoverflow.com/questions/895659/how-do-i-block-or-restrict-special-characters-from-input-fields-with-jquery – James Jan 11 '21 at 20:25
  • @OfirBaruch - that might work. Are you good at regular expressions? –  Jan 11 '21 at 20:25
  • @James, his expression has `"^[a-zA-Z0-9]+$"`. What is the `+$` for? And his is for key press. My issue is when customers paste in data. They aren't generally key pressing in a tab –  Jan 11 '21 at 20:27
  • The first answer won't handle paste. Check the others to see what your options are. – James Jan 11 '21 at 20:33
  • Who closed my question? Mine is associated with a PASTE event, not like the "duplicate question" that someone stuck on here. –  Jan 11 '21 at 21:05
  • @James - none of the answers work for a paste. I have created a jsfiddle project that allows me to quickly try all of the answers on the page you linked and the page someone else linked. I'm not getting any of those to work. My question isn't the same as the others. Why was it closed? –  Jan 11 '21 at 21:47

0 Answers0