Hot questions for Using JTextField in validation

Question:

Currently I am using the DocumentListener on every textfield, to live validate the users input, but I am thinking there must be a smarter way, since I am repeating my self so much.

Is there a smarter way of doing it?

nameJTextField.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void insertUpdate(DocumentEvent e) {
            validateName(nameJTextField.getText());
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            validateName(nameJTextField.getText());
        }

        @Override
        public void changedUpdate(DocumentEvent e) {

        }

        private void validateName(String name) {
             if (name.matches("^[A-ZÆØÅa-zæøå0-9]{2,40}$")) {
                 errorNameJLabel.setText("");
             } else {
                 errorNameJLabel.setText("Min 2 and max 40 letters and numbers");
             }
        }
    });

Answer:

since I am repeating my self so much.

Create a generic DocumentListener that you can add to any text field That is:

  1. The validateName(...) method should be defined in the DocumentListener
  2. Don't use the text field to get the text. Instead you can get the text from the Document. The DocumentEvent has a reference to the Document.

Also, you would not do the validation in the changedUpdate(...) method. That method is only used for a change of attributes (font, color etc) in the text when using a JTextPane or JEditorPane.

Without knowing the details of your validation it is hard to give a more specific answer.

Question:

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
                      }
                }
            });

Answer:

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.

Question:

I need to validate a JTextField by allowing the user to input only cnic number according to this format 12345-1234567-1, i am using this regular expression but it is not worked. this is my function

private void idSearchKeyPressed(java.awt.event.KeyEvent evt) {
    String cnicValidator = idSearch.getText();

    if (cnicValidator.matches("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$")) {
        idSearch.setEditable(true);
    }
    else {
        idSearch.setEditable(false);
    }        
}

Answer:

Use a JFormattedTextField combined with a MaskFormatter to restrict the input to begin with.

Something like this:

final JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final MaskFormatter mask;
        try {
            mask = new MaskFormatter("#####-#######-#");
        } catch (ParseException e) {
            throw new RuntimeException("Invalid format mask specified", e);
        }

        // You can optionally set a placeholder character by doing the following:
        mask.setPlaceholderCharacter('_');
        final JFormattedTextField formattedField = new JFormattedTextField(mask);

        frame.setSize(100, 100);
        frame.add(formattedField);
        frame.setVisible(true);

Question:

I have done a sample project in netbeans of registration. In the jtextfield1 is the user id and Jtextfiled7 is country, Both must in characters not in numeric or not allowed spaces and special characters.how it is possible?


Answer:

You can use JFormattedTextField or you can code inside the JTextField's KeyTyped event

jTextField.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyTyped(java.awt.event.KeyEvent evt) {

         if(!(Character.isLetter(evt.getKeyChar()))){
                evt.consume();
            }
        }
    });

Question:


Answer:

You can use an InputVerifier for this

public class Main extends JFrame {
    private JTextField textField1 = new JTextField();
    private JTextField textField2 = new JTextField();

    public Main() {
        setSize(200,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(textField1, BorderLayout.NORTH);
        add(textField2, BorderLayout.SOUTH);
        textField1.setInputVerifier(fieldVerifier);
    }

    InputVerifier fieldVerifier = new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField temp = (JTextField)input;
            try {
                int number = Integer.parseInt(temp.getText());
                return true;
            }
            catch(NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "You MUST input only numbers!");
            }
            return false;
        }
    };

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
}