Search code examples
javavalidationjtextfield

How to validate a Jtextfield to only allow letters in Java?


Trying to make this field only allow letters and there is an error on the " (c !='[a-zA-Z]+') " saying invalid character constant

textField_CustomerFirstName = new JTextField();
            textField_CustomerFirstName.setBounds(152, 100, 273, 22);
            textField_CustomerFirstName.setColumns(10);
            contentPane.add(textField_CustomerFirstName);
            textField_CustomerFirstName.addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e) {
                    // allows only numbers and back space
                     char c = e.getKeyChar();
                      if ( ((c !='[a-zA-Z]+') && (c != KeyEvent.VK_BACK_SPACE)) {
                         e.consume();  // ignore event
                      }
                }
            });

Solution

  • First, there is a difference between event.getKeyChar() and event.getKeyCode(). Second, you can use the static methods in java.lang.Character, and I believe you may be after the following:

    int code = e.getKeyCode();
    char c = e.getKeyChar();
    if(!Character.isLetter(c) && code!=KeyEvent.VK_BACK_SPACE) {
        e.consume();  // ignore event
    }
    

    You may also want to investigate whether Character.isAlphabetic is suitable for your purposes.