Jtextfield null field validation

Asked

Viewed 2,905 times

2

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

Method of 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 the values of the fields :

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 if I leave all fields null, it performs the registration, I believe it may be because it is a void method, but I’m not sure ...

2 answers

3

To facilitate validation, if more fields are included or if you have to validate other screens, you can use a utility method by passing the JTextField desired:

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

Calling it that:

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 necessary because when calling isEmpty() in a JTextField with blank spaces, is returned false!

1


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

Therefore, to check whether this field has anything typed or not, you should check whether the return of getText() is also empty.

Think of the written logic of if:

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();
 }

Remembering that one should always validate first if a field is null before checking if this same field is empty, because if somewhere in your code one of these fields is configured with value null, when validating again, it will burst NullPointerException when it’s time to check if it’s empty.

  • My intention is just to call the method eventosForm(); if none field is empty and null, so the logic would not replace all or for and ?

  • 1

    @Danielsantos not, because a field can be null or empty, are different states. A string is empty when its size is 0, and null when it has no value in it. But between the pairs of validations in each field, you should use the &&.

  • Still registering, even if I put the && between pairs of each field ...

  • @Danielsantos forgive me the misconception, the code really was having problems in boolean logic, had done without testing before. Now it is correct.

  • It is necessary to use Trim() as white spaces cause isEmpty() to return false.

  • @hlucasfranca well remembered, thanks for the warning :)

  • @Danielsantos if the answer answered, it would be interesting to mark it as accepted, thus, serve as reference for other users :)

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.