Matthew Pigram
Matthew Pigram

Reputation: 1430

form validation not working correctly

I am writing a simple GUI using netbeans and Java SE, i cannot seem to get input validation to work correctly. I have a JTextField and 2 JPasswordField objects, I want to check that any of these fields arent empty when the user hits the submit button. It works properly for the password fields if they are left empty, however if i input something into the username field, it prints data has been submitted, when the other form elements have not been filled with data. Here is the code below, any assistance would be greatly appreciated....

// test that none of the fields are empty before submitting form data
if (!username_input.getText().isEmpty() && !password_input1.getPassword().toString().isEmpty() 
                && !password_input2.getPassword().toString().isEmpty())
        {
            System.out.println("Data has been submitted!");
        }
        else
        {
            System.out.println("Form has not been filled in correctly!\nPlease try again");
        }

Upvotes: 0

Views: 327

Answers (2)

Zaz Gmy
Zaz Gmy

Reputation: 4356

use something like

!username_input.getText().toString().equals("")&& 
!new String(password_input1.getPassword()).equals("") &&
!new String(password_input2.getPassword()).equals("")

Upvotes: 1

Paul Vargas
Paul Vargas

Reputation: 42060

Change the boolean expression to:

!username_input.getText().isEmpty() && 
password_input1.getPassword().lenght == 0 &&   
password_input2.getPassword().lenght == 0

The method getPassword() returns a char array and you need check the lenght == 0 for empty values in the JPasswordField.

Upvotes: 0

Related Questions