Search code examples
javaswingjtextfield

Java - How to enforce JTextField to have alphanumeric values


I want the JTextField to accept only Letters and Numbers. But it SHOULD contain both. It should not contain not letters only nor numbers only.


Solution

  • 1) Try adding a key listener to your text field. See if it helps.
    Once the user has finished typing, check the values of both flags.

    private boolean hasLetter = false;
    private boolean hasDigit = false;
    
    public void keyTyped(KeyEvent evt) {
            char c = evt.getKeyChar();
    
            if (Character.isLetter(c)) {
                // OK
                hasLetter = true;
            } else if (Character.isDigit(c)) {
                // OK
                hasDigit = true;                
            } else {
                // Ignore this character
                evt.consume();
            }
    }
    

    2) Alternatively, just accept any character and validate at the very end
    when the user has finished typing. For this you can use a regular expression.

    "a1b2c".matches("^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]+$")
    "123".matches("^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]+$")
    "abc".matches("^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]+$")