Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
How to remove special characters from input fields while pasting?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

$('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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!