1

I want to restrict user from entering Special characters in SWT text field. I tried the below code, but it is not working....

   txt_Appname.addKeyListener(new KeyAdapter()
    {
        public void keyTyped(KeyEvent e) {
            char chars = e.character;
            if (!Character.isLetterOrDigit(chars)) {
                e.doit = false;
                return;
            }
        }
    });

can any one give me the working code for restricting special characters in SWT textfield ?

greg-449
  • 109,219
  • 232
  • 102
  • 145
Shabeeralimsn
  • 797
  • 4
  • 11
  • 32
  • Does [this post](http://stackoverflow.com/questions/1795402/java-check-a-string-if-there-is-a-special-character-in-it) helps – Chandrayya G K Mar 24 '14 at 08:37

1 Answers1

3

Use a VerifyListener:

txt_Appname.addVerifyListener(new VerifyListener() {
  @Override
  public void verifyText(VerifyEvent e) {
      String text = e.text;
      for (int i = 0; i < text.length(); i++) {
         if (!Character.isLetterOrDigit(text.charAt(i)) {
            e.doit = false;
            return;
         }
      }
  }
});
greg-449
  • 109,219
  • 232
  • 102
  • 145