user3167732
user3167732

Reputation: 33

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.

Upvotes: 1

Views: 3823

Answers (3)

peter.petrov
peter.petrov

Reputation: 39437

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]+$")

Upvotes: 2

Paul Samsotha
Paul Samsotha

Reputation: 208944

You should be using a DocumentFilter which will filter in real time, the input to the text field.

See some of the swing+jtextfield+documentfilter tagged questions for some other sources.

Here's a simple example

public class FieldFilterDemo {

    public static void main(String[] args) {
        JTextComponent field = getFilteredField();
        JOptionPane.showMessageDialog(null, field);

    }

    static JTextComponent getFilteredField() {
        JTextField field = new JTextField(15);
        AbstractDocument doc = (AbstractDocument) field.getDocument();
        doc.setDocumentFilter(new DocumentFilter() {
            public void replace(FilterBypass fb, int offs, int length,
                    String str, AttributeSet a) throws BadLocationException {
                super.replace(fb, offs, length,
                        str.replaceAll("[^0-9a-zA-Z]+", ""), a);
            }

            public void insertString(FilterBypass fb, int offs, String str,
                    AttributeSet a) throws BadLocationException {
                super.insertString(fb, offs,
                        str.replaceAll("[^0-9a-zA-Z]+", ""), a);
            }
        });
        return field;
    }
}

Upvotes: 3

keuleJ
keuleJ

Reputation: 3486

Try to use a JFormattedTextField with the corresponding NumberFormat.

Upvotes: 1

Related Questions