Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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);
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!