Question

When I tried to validating the text fields, in the empty text fields if I press,backspace or ctrl keys,It's giving the warning message which has to be actually given when entering the numbers instead alphabets.

How to avoid these alerts?

I am validating using regex

fname.getText().matches("^[ A-z]+$")

For another Textfield

zipcode.getText().matches("[ 0-9a-zA-Z]{7}")

Help me to solve my issue or if any better solution is available for validating, please suggest.

Was it helpful?

Solution

"or if any better solution is available for validating, please suggest."

Don't use KeyListener with JTextFields For "real time validation" you should look into using a DocumentFilter for the underlying Document of the JTextField.

There are many examples here on SO that you can search for.


UPDATE

Here's an example using your regex, where it allows only up to 7 letters an numbers

import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class ValidateTextField {

    public ValidateTextField() {
        JFrame frame = new JFrame();
        JTextField field = createTextField();
        frame.setLayout(new GridBagLayout());
        frame.add(field);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private JTextField createTextField() {
        final JTextField field = new JTextField(15);
        ((AbstractDocument) field.getDocument()).setDocumentFilter(new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int off, String str, AttributeSet attr)
                    throws BadLocationException {
                int length = field.getDocument().getLength();
                if (length + str.length() <= 7) {
                    fb.insertString(off, str.replaceAll("[^0-9a-zA-Z]", ""), attr);  // remove non-digits
                }
            }

            @Override
            public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)
                    throws BadLocationException {
                int length = field.getDocument().getLength();
                if (length + str.length() <= 7) {
                    fb.replace(off, len, str.replaceAll("[^0-9a-zA-Z]", ""), attr);  // remove non-digits
                }
            }
        });
        return field;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ValidateTextField();
            }
        });
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top