Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty String validation for Multiple JTextfield

Is there a way to validate a number of JTextfields in java without the if else structure. I have a set of 13 fields, i want an error message when no entry is given for any of the 13 fields and to be able to set focus to that particular textbox. this is to prevent users from entering empty data into database. could someone show me how this can be achieved without the if else structure like below.

if (firstName.equals("")) {
    JOptionPane.showMessageDialog(null, "No data entered");
} else if (lastName.equals("")) {
    JOptionPane.showMessageDialog(null, "No data entered");
} else if (emailAddress.equals("")) {
    JOptionPane.showMessageDialog(null, "No data entered");
} else if (phone.equals("")) {
   JOptionPane.showMessageDialog(null, "No data entered");
} else {
 //code to enter values into MySql database

the above code come under the actionperformed method a of a submit registration button. despite setting fields in MySQL as NOT NULL, empty string were being accepted from java GUI. why is this? i was hoping perhaps an empty string exception could be thrown from which i could customise a validation message but was unable to do so as empty field were being accepted.

Thanks

like image 573
Hoody Avatar asked Dec 25 '12 17:12

Hoody


Video Answer


2 Answers

Just for fun a little finger twitching demonstrating a re-usable validation setup which does use features available in core Swing.

The collaborators:

  • InputVerifier which contains the validation logic. Here it's simply checking for empty text in the field in verify. Note that
    • verify must not have side-effects
    • shouldYieldFocus is overridden to not restrict focus traversal
    • it's the same instance for all text fields
  • a commit action that checks the validity of all children of its parent by explicitly invoking the inputVerifier (if any) and simply does nothing if any is invalid
  • a mechanism for a very simple though generally available error message taking the label of the input field

Some code snippets

// a reusable, shareable input verifier
InputVerifier iv = new InputVerifier() {

    @Override
    public boolean verify(JComponent input) {
        if (!(input instanceof JTextField)) return true;
        return isValidText((JTextField) input);
    }

    protected boolean isValidText(JTextField field) {
        return field.getText() != null && 
                !field.getText().trim().isEmpty();
    }

    /**
     * Implemented to unconditionally return true: focus traversal
     * should never be restricted.
     */
    @Override
    public boolean shouldYieldFocus(JComponent input) {
        return true;
    }

};
// using MigLayout for lazyness ;-)
final JComponent form = new JPanel(new MigLayout("wrap 2", "[align right][]"));
for (int i = 0; i < 5; i++) {
    // instantiate the input fields with inputVerifier
    JTextField field = new JTextField(20);
    field.setInputVerifier(iv);
    // set label per field
    JLabel label = new JLabel("input " + i);
    label.setLabelFor(field);
    form.add(label);
    form.add(field);
}

Action validateForm = new AbstractAction("Commit") {

    @Override
    public void actionPerformed(ActionEvent e) {
        Component source = (Component) e.getSource();
        if (!validateInputs(source.getParent())) {
            // some input invalid, do nothing
            return;
        }
        System.out.println("all valid - do stuff");
    }

    protected boolean validateInputs(Container form) {
        for (int i = 0; i < form.getComponentCount(); i++) {
            JComponent child = (JComponent) form.getComponent(i);
            if (!isValid(child)) {
                String text = getLabelText(child);
                JOptionPane.showMessageDialog(form, "error at" + text);
                child.requestFocusInWindow();
                return false;
            }
        }
        return true;
    }
    /**
     * Returns the text of the label which is associated with
     * child. 
     */
    protected String getLabelText(JComponent child) {
        JLabel labelFor = (JLabel) child.getClientProperty("labeledBy");
        return labelFor != null ? labelFor.getText() : "";
    }

    private boolean isValid(JComponent child) {
        if (child.getInputVerifier() != null) {
            return child.getInputVerifier().verify(child);
        }
        return true;
    }
};
// just for fun: MigLayout handles sequence of buttons 
// automagically as per OS guidelines
form.add(new JButton("Cancel"), "tag cancel, span, split 2");
form.add(new JButton(validateForm), "tag ok");
like image 197
kleopatra Avatar answered Sep 28 '22 00:09

kleopatra


There are multiple ways to do this, one is

 JTextField[] txtFieldA = new JTextField[13] ;
 txtFieldFirstName.setName("First Name") ; //add name for all text fields
 txtFieldA[0] = txtFieldFirstName ;
 txtFieldA[1] = txtFieldLastName ;
 ....

 // in action event
 for(JTextField txtField : txtFieldA) {
   if(txtField.getText().equals("") ) {
      JOptionPane.showMessageDialog(null, txtField.getName() +" is empty!");
      //break it to avoid multiple popups
      break;
   }
 }

Also please take a look at JGoodies Validation that framework helps you validate user input in Swing applications and assists you in reporting validation errors and warnings.

like image 29
vels4j Avatar answered Sep 27 '22 22:09

vels4j