Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...