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

135
Vistas
How can I validate field input against a regex when pasting?

I want to validate an input field with regex (replacing all vowels). The input should always be matched against that regex, regardles if typed into or pasted into that field.

I know how to deal with the typing part, but I need help for copy - paste. All vowels should be skipped (e.g.: "abcde" copy --> "bcd" paste)

    $('document').ready(function(){
      var pattern = /[aeiou]/ig;

      $("#input").on("keypress keydown", function (e) {
        if (e.key.match(pattern) !== null) {
          e.preventDefault();
        }
      });
      
      $("#input").on("paste", function (e) {
        var text = e.originalEvent.clipboardData.getData('Text');
        e.preventDefault();

        //TODO... replace all vowels
        console.log(text);
      });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='input'/>

At first i tried to replace them and just set the value with $('#input').val($('#input').val() + copiedValue), but this only works if the cursor is at the end of the input.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

A one in all solution subscribes to the input event. In addition to the sanitizing tasks the handler has to take care of reestablishing the input fields exact or most expected cursor/caret position in order to not break the user experience ...

function getSanitizedValue(value) {
  return value.replace(/[aeiou]/ig, '');
}

function handleInput(evt) {
  evt.preventDefault();

  const elmNode = evt.currentTarget;

  const currentValue = elmNode.value;
  const sanitizedValue = getSanitizedValue(currentValue);

  if (currentValue !== sanitizedValue) {
    const diff = sanitizedValue.length - currentValue.length;
    const { selectionStart, selectionEnd } = elmNode;

    elmNode.value = sanitizedValue;

    elmNode.selectionStart =
      (selectionStart + diff > 0) ? selectionStart + diff : selectionStart;
    elmNode.selectionEnd =
      (selectionEnd + diff > 0) ? selectionEnd + diff : selectionEnd;
  }
}

$('document')
  .ready(() => {

    $("#input").on("input", handleInput);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='input'/>

about 4 years ago · Juan Pablo Isaza Denunciar

0

One method would be to manipulate the value of the text field from the paste event:

$('document').ready(function(){
      var pattern = /[aeiou]/ig;

      $("#input").on("keypress keydown", function (e) {
        if (e.key.length == 1 && !e.ctrlKey && !e.altKey && e.key.match(pattern) !== null) {
          e.preventDefault()
        }
      });
      
      $("#input").on("paste", function (e) {
        var text = e.originalEvent.clipboardData.getData('Text').replace(pattern, "");
        e.preventDefault();
        let input = e.originalEvent.target,
            start = input.selectionStart,
            end = input.selectionEnd;
        input.value = input.value.substr(0, start) + text + input.value.substr(end);
        input.selectionStart = start + text.length;
        input.selectionEnd = input.selectionStart;
        //TODO... replace all vowels
        console.log(text, input.value);
      });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='input'/>

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