【问题标题】:How to validate a jtextfield to specific format?如何将 jtextfield 验证为特定格式?
【发布时间】:2016-08-11 15:15:59
【问题描述】:

我需要通过允许用户根据此格式 12345-1234567-1 仅输入 cnic 编号来验证 JTextField,我正在使用此正则表达式,但它不起作用。这是我的功能

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

【问题讨论】:

    标签: java swing validation jtextfield


    【解决方案1】:

    使用JFormattedTextField 结合MaskFormatter 来限制输入的开头。

    类似这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 2016-12-01
      • 2016-01-13
      • 2018-03-17
      • 2012-12-31
      相关资源
      最近更新 更多