Search code examples
javaswingjframejtablejtextfield

How to validate a jtextfield to accept only pakistan cnic 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);
    }        
}

kindly provide me some guidence how to validate my jtextfield...thanks


Solution

  • An alternative solution to validating post-input would be to use a JFormattedTextField combined with a MaskFormatter to restrict the input to begin with.

    The code to create one of these would be something along the lines of:

    import java.text.ParseException;
    
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.text.MaskFormatter;
    
    public class Demo {
    
        public static void main(String[] args){
    
            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);
        }
    }
    

    The format mask # only accepts digits (specifically, it accepts any character where Character.isDigit(char) returns true), and forbids any non-digit from being entered.