Search code examples
javaswingvalidationjtextfield

How to validate a jtextfield to specific format?


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

Solution

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