JTextField null field validation

2

On my system, I have a window and a controller, but for some reason, it is never throwing the error, as expected:

Method that performs validation:

private void validacao(){
    if((form.txtNome.getText() != null) && (form.txtEnd.getText() != null) && (form.txtTel.getText() != null)){
        eventosForm();
    }else{
        JOptionPane.showMessageDialog(null, "Todos os campos devem estar preenchidos !");
    }
}

Method that takes field values:

private void eventosForm(){
    form.btnCadastrar.addActionListener(new ActionListener() {  
        @Override
        public void actionPerformed(ActionEvent e) {
            Cliente cliente = new Cliente();
            cliente.setNome(form.txtNome.getText());
            cliente.setEndereco(form.txtEnd.getText());
            cliente.setTelefone(form.txtTel.getText());
            clienteDB.add(cliente);
            form.setVisible(false);
        }
    });
}

As I said before, even though I leave all fields empty, it performs the registration, I believe it may be because it is a void method, but I'm not sure ...

    
asked by anonymous 07.04.2016 / 23:06

2 answers

1

When you start a JTextField without passing any text value to it (eg new JTextField() ), the field starts as empty.

So, to check whether or not this field is typed, you should check that the getText() return is also empty.

Think of if written logic:

Se:   
  (campo1 está nulo ou campo1 está vazio) ou (campo2 está nulo ou campo2 está vazio) 
então:
   exiba a mensagem;
senão:
   chame o método eventosForm()

That would be in code:

 if ((form.txtNome.getText() == null || form.txtNome.getText().trim().isEmpty()) ||
  (form.txtEnd.getText() == null || form.txtEnd.getText().trim().isEmpty()) ||
  (form.txtTel.getText() == null || form.txtTel.getText().trim().isEmpty())) {
  JOptionPane.showMessageDialog(null, "Todos os campos devem estar preenchidos !");
 } else {
  eventosForm();
 }

Remember that you should always validate first if a field is null before checking if this field is empty, because if somewhere in your code one of these fields is set to null , when validating again, it will pop NullPointerException when checking to see if it is empty.

    
07.04.2016 / 23:21
3

For ease of validation, if more fields are included or if you need to validate other screens, you can use a utility method by passing the desired JTextField :

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

Calling like this:

if ( estaVazio(form.txtNome.getText()) || estaVazio(form.txtEnd.getText()) 
    || estaVazio(form.txtTel.getText())) {
    JOptionPane.showMessageDialog(null, "Todos os campos devem estar preenchidos !");
} else {
    eventosForm();
}

The trim() is also required because when calling isEmpty() in a JTextField with whitespace, is returned > false !

    
08.04.2016 / 02:09