Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

108
Vistas
Javascript Regex input text letters and numbers only

I'm using this script to only allow my input text letters and numbers

function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
       textbox.addEventListener(event, function() {
              if (inputFilter(this.value)) {
                this.oldValue = this.value;
                this.oldSelectionStart = this.selectionStart;
                this.oldSelectionEnd = this.selectionEnd;
                console.log("If 1");
              } else if (this.hasOwnProperty("oldValue")) {
                this.value = this.oldValue;
                this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                console.log("if 2");
              } else {
                  console.log("if 3");
                this.value = "";
              }
            });
          });
    }
    
    setInputFilter(document.getElementById("frm_nuevo_proveedor:j_idt35"), function(value) {
          return /^[^\W_]+$/i.test(value); 
    });

My problem is that once I type the first value it doesn't let me erase it anymore

Example

So the first value won't let me delete it.

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

When you attempt to remove the last character, the RegExp returns false because it is not set to accept blank strings. This causes the script to restore the oldValue, which would be that single letter.

The simplest fix seems to be updating the RegExp used as the filter. This should work for you, though I'm no expert on regular expressions so there may be a better way:

setInputFilter(document.getElementById("testEl"), function(value) {
  return /(^$|^[^\W_]+$)/i.test(value);
});
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos