Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda