[SOLVED] How to remove special characters from input fields while pasting?

Issue

I’m trying to implement functionality where if a user pastes text it should remove <, >, $ and !.

The following code works on all inputs. Currently it disables the paste function.

function specialCharRestriction() {
  setTimeout(function(e) {
    $('input, textarea').bind("cut copy paste", function(e) {
      e.preventDefault();
    });
    
    $('input:not([type=password]), textarea').on('keypress', function(e) {
      var blockSpecialRegex = /[!$(){}[\]:;<+?\\>]/;
      var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
      
      if (blockSpecialRegex.test(key)) {
        e.preventDefault();
        return false;
      }
    });
  }, 500);
}

Instead, I want something like this:

$('input').val().replace(regex, '');

This way it can be applied on all inputs and I don’t have to select all the inputs one by one. There are more than 100 fields declared in my project so please help with some generic code which can be applied on all input fields.

Edit: I want that whenever someone pastes <Naruto> then only Naruto should be pasted and <> should be omitted. following code only works once, and then special characters are being pasted.

Solution

$('input, textarea').bind("input", function(e) {
  var blockSpecialRegex = /[!$(){}[\]:;<+?\\>]/g;
  let txtOrig = $(this).val();
  let txtFinal = txtOrig.replace(blockSpecialRegex, '');
  if (txtOrig !== txtFinal) {
    // Some blocked special chars was found and removed
    // Warning: this will move the cursor to the end!
    $(this).val(txtFinal);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
input1:<input id="txt1"><br>
input2:<input id="txt2"><br>
input3:<input id="txt3"><br>
textarea1:<textarea id="txt4"></textarea><br>
textarea2:<textarea id="txt5"></textarea><br>
textarea3:<textarea id="txt6"></textarea><br>

Answered By – Manuel Romeiro

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *