user982467
user982467

Reputation: 142

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.

Upvotes: 1

Views: 539

Answers (2)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59988

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.

Upvotes: 1

Mikenno
Mikenno

Reputation: 294

as i understand your question what u want is to match the character types that are inputted, for this i would suggest to take a look at the String.matches see javaDoc using this you can setup a function that checks the input for any regrex epression and returns true or false, if this is NOT what you wanted i'm afraid i don't understand the question

Upvotes: 0

Related Questions