Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda