By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,651 Members | 1,368 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,651 IT Pros & Developers. It's quick & easy.

disabling keys: limit user to alphabet and numbers

P: 59
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?


Expand|Select|Wrap|Line Numbers
  1. if(keys == KeyEvent.VK_SHIFT || keys == KeyEvent.VK_CAPS_LOCK || keys ==KeyEvent.VK_LEFT ||
  2.    keys ==KeyEvent.VK_RIGHT || keys ==KeyEvent.VK_DOWN || keys ==KeyEvent.VK_UP   .....)  //more button to disable
  3. {
  4. }
  5. else{  //store the char in array            
  6.     username[z] = e.getKeyChar();
  7.     z++;
  8. }
  9.  
May 3 '13 #1
Share this Question
Share on Google+
4 Replies


Rabbit
Expert Mod 10K+
P: 12,421
Rather than blacklisting the keys, whitelist the ranges that are allowed.
May 3 '13 #2

P: 59
whats whitlist the range? is there tutorial online how to do this?
May 3 '13 #3

Nepomuk
Expert 2.5K+
P: 3,112
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:
Expand|Select|Wrap|Line Numbers
  1. if( (keys >= KeyEvent.VK_0 && keys <= KeyEvent.VK_9)
  2.  || (keys >= KeyEvent.VK_A && keys <= KeyEvent.VK_Z)) {
  3.   // do stuff
  4. } else {
  5.   // Tell the user he pressed a deactivated key. Or don't. Your choice.
  6. }
May 4 '13 #4

P: 59
ah i see. i didnt knew we could do this. thanks alot guys
May 4 '13 #5

Post your reply

Sign in to post your reply or Sign up for a free account.