martin doherty
martin doherty

Reputation: 27

stop user entering special characters

I know that the code below will prohibit the user from entering digits but how do I manipulate it to prohibit special characters, e.g. ,./;'#[]-=<>?:@~{}_+.

txtUserName.addKeyListener(new KeyAdapter() {
   public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      if (Character.isDigit(e.getKeyChar()))
            e.consume();
   }
});

Upvotes: 1

Views: 1605

Answers (2)

Ethan Brouwer
Ethan Brouwer

Reputation: 1005

Here's the Code:

txtUserName.addKeyListener(new KeyAdapter() {
   public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      if (!Character.isLetterOrDigit(c))
            e.consume();
   }
});

Just use a different function.

Upvotes: 1

Kelsey Francis
Kelsey Francis

Reputation: 522

Check if ",./;'#[]-=<>?:@~{}_+".indexOf(c) != -1.

See String#indexOf(int).

Upvotes: 0

Related Questions