JavaScript: input validation in the keydown event

Posted by c411 on Stack Overflow See other posts from Stack Overflow or by c411
Published on 2010-06-08T13:43:50Z Indexed on 2010/06/08 14:52 UTC
Read the original article Hit count: 332

Hi,

I'm attempting to do info validation against user text input in the process of keydown event. The reason that I am trying to validate in the keydown event is because I do not want to display the characters those that are considered to be illegal in the input box at the beginning.

The validation I am writing is like this,

function validateUserInput(){
   var code = this.event.keyCode;
    if ((code<48||code>57) // numerical
      &&code!==46 //delete
      &&code!==8  //back space
      &&code!==37 // <- arrow 
      &&code!==39) // -> arrow
   {
     this.event.preventDefault();        
    }
}

I can keep going like this, however I am seeing drawbacks on this implmentation. Those are, for example,

  1. Conditional statement become longer and longer when I put more conditions to be examined.
  2. keyCodes can be different by browsers.
  3. I have to not only check what is not legal but also have to check what are exceptionals. In above examples, delete,backspace, and arrow keys are exceptionals.

But the feature that I don't want to lose is having not to display the input in the textarea unless it passes the validation. (In case the user try to put illegal characters in the textarea, nothing should appear at all) That is why I am not doing validation upon keyup event.

So my question is,

  1. Are there better ways to validate input in keydown event than checking keyCode by keyCode?
  2. Are there other ways to capture the user inputs other than keydown event before browser displays it? And a way to put the validation on it?

Thanks for the help in advance.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-events