Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading