Empty String validation for Multiple JTextfield

痞子三分冷 提交于 2019-11-28 03:51:53

问题


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


回答1:


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



回答2:


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.




回答3:


Take an array of these three JTextField, I am giving an overview

JTextField[] fields = new JTextField[13] 
field[0] = firstname;
field[1] = lastname; //then add remaining textfields

for(int i = 0; i < fields.size(); ++i) {
if(fields[i].getText().isEmpty())
   JOptionPane.showMessageDialog(null, "No data entered");
}

Correct me if i'm wrong, I am not familiar with Swing or awt.HTH :)




回答4:


Here is one way to do it:

public static boolean areAllNotEmpty(String... texts)
{
    for(String s : texts) if(s == null || "".equals(s)) return false;
    return true;
}

// ...

if(areAllNotEmpty(firstName, lastName, emailAddress, phone))
{
    JOptionPane.showMessageDialog(null, "No data entered");
}


来源:https://stackoverflow.com/questions/14032757/empty-string-validation-for-multiple-jtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!