disabling keys: limit user to alphabet and numbers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • game2d
    New Member
    • Apr 2013
    • 59

    disabling keys: limit user to alphabet and numbers

    when user press can key than the code below gets the key user just pressed. the problem is that i want to only limit user to press alphabet and numbers. so i want to disable weird char ex left, right, up, @,$,!,%..... as you can see this will take up alot of if statments. is there better way to do this?


    Code:
    if(keys == KeyEvent.VK_SHIFT || keys == KeyEvent.VK_CAPS_LOCK || keys ==KeyEvent.VK_LEFT ||
       keys ==KeyEvent.VK_RIGHT || keys ==KeyEvent.VK_DOWN || keys ==KeyEvent.VK_UP   .....)  //more button to disable
    {
    }
    else{  //store the char in array			
    	username[z] = e.getKeyChar();
    	z++;
    }
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Rather than blacklisting the keys, whitelist the ranges that are allowed.

    Comment

    • game2d
      New Member
      • Apr 2013
      • 59

      #3
      whats whitlist the range? is there tutorial online how to do this?

      Comment

      • Nepomuk
        Recognized Expert Specialist
        • Aug 2007
        • 3111

        #4
        I don't know of a tutorial, but what Rabbit means is the following:
        As you can see in the KeyEvent API docs, all of these events are basically integers and can be compared as such. So you can check which keys should be allowed (hence a whitelist) by something like this:
        Code:
        if( (keys >= KeyEvent.VK_0 && keys <= KeyEvent.VK_9)
         || (keys >= KeyEvent.VK_A && keys <= KeyEvent.VK_Z)) {
          // do stuff
        } else {
          // Tell the user he pressed a deactivated key. Or don't. Your choice.
        }

        Comment

        • game2d
          New Member
          • Apr 2013
          • 59

          #5
          ah i see. i didnt knew we could do this. thanks alot guys

          Comment

          Working...