Search code examples
javaswingvalidationjoptionpane

How to add validation to multiple text fields in JOptionPane?


I have the following method which pops up a window when a button is clicked.

public void cardPopUp() {
    String[] cardTypes = {"Visa", "Mastercard", "Electron", "Cashcard"};

    JComboBox combo = new JComboBox(cardTypes);
    JTextField field1 = new JTextField("");
    JTextField field2 = new JTextField("");
    JTextField field3 = new JTextField("");
    JTextField field4 = new JTextField("");
    JTextField field5 = new JTextField("");

    JPanel panel = new JPanel(new GridLayout(0, 2));
    panel.add(new JLabel("Card Type:"));
    panel.add(combo);
    panel.add(new JLabel("Cardholder Name:"));
    panel.add(field1);
    panel.add(new JLabel("Card Number:"));
    panel.add(field2);
    panel.add(new JLabel("Month Expiry:"));
    panel.add(field3);
    panel.add(new JLabel("Year Expiry:"));
    panel.add(field4);
    panel.add(new JLabel("CVC:"));
    panel.add(field5);

    int input = JOptionPane.showConfirmDialog(MainActivity.this, panel, "Card Payment",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (input == JOptionPane.OK_OPTION) {
            Basket.orderNo+=1;
            dispose();
            new OrderConfirmationScreen().setVisible(true);
        } else {
            System.out.println("Payment Cancelled");
        }
}

How can i add validation so that the fields are checked to see if correct data was entered for a card payment. For example, field1 should only allow text, field2 should only allow a 16 digit number and so on.

I'm guessing i would need to create more methods that validate each field and then just call the method in cardPopUp() method.


Solution

  • For example :

    field1 should only allow text

    if(field1.getText().matches("\\w+\\.?")){
      ...
    }else{...}
    

    field2 should only allow a 16 digit number

    if(field2.getText().matches("(\\d{16})")){
      ...
    }else{...}
    

    And so on.