Checking of empty textbox - java

I am trying to show a messagebox when either the username or password textbox is empty but when I run the project the only textbox showing is "JOptionPane.showMessageDialog(null,"Your Username or Password is incorrect");" Please help and Thank You!
private void jButton1ActionPerformed(ActionEvent evt) {
String user=txtUsername.getText();
char[] pass=txtPassword.getPassword();
if(user == null) {
JOptionPane.showMessageDialog(null,"Username Field is empty");
} else if(pass==null) {
JOptionPane.showMessageDialog(null,"Password Field is empty");
} else {
String sql="select * from account where username=? and password=?";
try{
pst=conn.prepareStatement(sql);
pst.setString(1,txtUsername.getText());
pst.setString(2,txtPassword.getText());
rs=pst.executeQuery();
if (rs.next()) {
GridlockMain a=new GridlockMain();
a.setVisible(true);
} else {
JOptionPane.showMessageDialog(null,"Your Username or Password is incorrect");
txtUsername.setText(null);
txtPassword.setText(null);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,e);
}
}
}

JTextField.getText() does not return null if you keep it empty. Try to check value using isEmpty method at if condition.
String user=txtUsername.getText();// It return empty String ""
// even no data is entered.
if(user.isEmpty){
JOptionPane.showMessageDialog(null,"Username Field is empty");
}
......

try this..
if(!user.length() > 0){
JOptionPane.showMessageDialog(null,"Username Field is empty");
}
else if(!pass.length > 0){
JOptionPane.showMessageDialog(null,"Password Field is empty");
}

I also struggled with the text Validation process. I found a very easy way to test this. Here, instead of using JOptionPane to show a message to the user, I just didn't allow them to enter, or press the button. Here's my code:
//Validate whether user Has input some information:
if(UserNameTA.getText() == null || UserNameTA.getText().trim().isEmpty())
{
btnEnter.setEnabled(false);
}
else
{
//Make a new JFrame for login
new ProfileHome().setVisible(true);
frame.dispose();
}
btnEnter.setEnabled(true);
I hope this at least guides you to your success.

It returns an empty string "" compare the
StringUtils.isEmpty(txtUsername.getText())

String user = txtUsername.getText();
String pw = txtPassword.getText();
if(user.isEmpty() || (pw.isEmpty()))
{
JOptionPane.showMessageDialog(null, "Your Username or Password is incorrect" );
}
else
{
//proceed to query

if (user.length() == 0) {
JOptionPane.showMessageDialog(null, "Username Field is empty");
} else if (pass.length() == 0) {
JOptionPane.showMessageDialog(null, "Password Field is empty");
}

Related

How do I develop this login interface?

I got a list(Employees) of employees(object of class Employee) and I try to iterate over that list so I can validate the entered information otherwise rise a message error, It does validate the information and logins in when right information but it raises an error in all others employees checked existent in the list.
String username = FieldUsername.getText();
String password = FieldPassword.getText();
Iterator<Employee> i = Employees.iterator();
while (i.hasNext()) {
Employee o = i.next();
if (o.getName().equals(username) & o.getPassword().equals(password)) {
if (o.getJob().equals("President")) {
JOptionPane.showMessageDialog(null, "Welcome");
UserPresident uno = new UserPresident();
uno.show();
this.dispose();
} else if (o.getJob().equals("Manager")) {
if (o.getArea().equals("Production")) {
JOptionPane.showMessageDialog(null, "Welcome");
UserProductionManager uno = new UserProductionManager();
uno.show();
}else if(o.getArea().equals("Marketing")){
JOptionPane.showMessageDialog(null, "Welcome");
UserMarketingManager uno = new UserMarketingManager();
uno.show();
}else{
JOptionPane.showMessageDialog(null, "Welcome");
UserHRManager uno = new UserHRManager();
uno.show();
}
} else {
JOptionPane.showMessageDialog(null, "Bienvenido");
UserEmployee uno = new UserEmployee();
uno.show();
}
} else {
JOptionPane.showMessageDialog(null, "Username or password is incorrect!");
FieldUsername.setText("");
FieldPassword.setText("");
}
}
Your code will go through each and every employee even if it is correct login it continues to look for another employee to match, you need to make it print Username or password is incorrect! after the loop is done and it hasn't found a match, you could do this by adding a boolean value before the loop and if a correct user was found then change the boolean to not print the Username or password is incorrect!, a simple example:
String username = FieldUsername.getText();
String password = FieldPassword.getText();
Iterator<Employee> i = Employees.iterator();
boolean isCorrectLoginFound = false // Checks for correct login
while (i.hasNext()) {
Employee o = i.next();
if (o.getName().equals(username) && o.getPassword().equals(password)) {
isCorrectLoginFound = true;
if (o.getJob().equals("President")) {
JOptionPane.showMessageDialog(null, "Welcome");
UserPresident uno = new UserPresident();
uno.show();
this.dispose();
break;
} else if (o.getJob().equals("Manager")) {
if (o.getArea().equals("Production")) {
JOptionPane.showMessageDialog(null, "Welcome");
UserProductionManager uno = new UserProductionManager();
uno.show();
break;
}else if(o.getArea().equals("Marketing")){
JOptionPane.showMessageDialog(null, "Welcome");
UserMarketingManager uno = new UserMarketingManager();
uno.show();
break;
}else{
JOptionPane.showMessageDialog(null, "Welcome");
UserHRManager uno = new UserHRManager();
uno.show();
break;
}
} else {
JOptionPane.showMessageDialog(null, "Bienvenido");
UserEmployee uno = new UserEmployee();
uno.show();
break;
}
}
}
if (!isCorrectLoginFound) {
JOptionPane.showMessageDialog(null, "Username or password is incorrect!");
FieldUsername.setText("");
FieldPassword.setText("");
}

if-else loop condition is not working using java swing?

I'm trying to fetch database records of user name and password and validate using if-else statement. Final else statement is not displaying message dialog. I'm stuck with this, suggest me a solution and say where i done mistake.
My complete code
String s1 = id.getText();
String s2 = new String(pass.getPassword());
try
{
Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/twitter_db","arunachalam","");
String sql = "select userid, password from user_reg where userid='"+s1+"'";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
if((rs.getString("userid").equals(s1)) && (rs.getString("password").equals(s2)))
{
dispose();
showMessageDialog(null,"Login Successfully");
new UserPage().setVisible(true);
}
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}
else
{
showMessageDialog(null,"Invalid User");
}
}
}
catch(Exception e)
{
showMessageDialog(null, e);
}
You checked same condition twice for user id and password so every time it checks first else if statement and it does't satisfy final else if.
Obeserve in your below piece of source code.
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}
May be you are trying for below code that i have updated
// check for user id not equal
else if((!rs.getString("userid").equals(s1)) && (rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect User Id");
}
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}

java tokens when is long no catch it

hello i am having a problem when trying to catch tokens from a html form , the form have 3 tokens to fill, password, repeatpassword and email the email token are giving me problems, if i fill an email short like 123#hotmail.com it work fine, but if i fill b0rtzito#hotmail.com it dont work and i dont know the reason, i tried with many combinations unssuccessfull, maybe someone can point me , thanks in advance.
if (command.startsWith("PasswordCreate2"))
{
StringTokenizer create = new StringTokenizer(command, " ");
String pass = null, repeat = null, email = null;
create.nextToken();
if (create.hasMoreTokens())
{
pass = create.nextToken();
}
if (create.hasMoreTokens())
{
repeat = create.nextToken();
}
if (create.hasMoreTokens())
{
email = create.nextToken();
}
if (!((pass == null) || (repeat == null) || (email == null)))
{
if (!pass.equals(repeat))
{
player.sendMessage("The password doesn't match with the repeated one!");
NpcHtmlMessage htm = new NpcHtmlMessage(0);
htm.setHtml(HtmCache.getInstance().getHtm(player.getHtmlPrefix(), htmlPath + "createPassword2.htm"));
player.sendPacket(htm);
return false;
}
if (pass.length() < 3)
{
player.sendMessage("The password is shorter than 3 chars! Please try with a longer one.");
NpcHtmlMessage htm = new NpcHtmlMessage(0);
htm.setHtml(HtmCache.getInstance().getHtm(player.getHtmlPrefix(), htmlPath + "createPassword2.htm"));
player.sendPacket(htm);
return false;
}
if (pass.length() > 30)
{
player.sendMessage("The password is longer than 30 chars! Please try with a shorter one.");
NpcHtmlMessage htm = new NpcHtmlMessage(0);
htm.setHtml(HtmCache.getInstance().getHtm(player.getHtmlPrefix(), htmlPath + "createPassword2.htm"));
player.sendPacket(htm);
return false;
}
if (!(email.contains("#") || email.contains(".")))
{
player.sendMessage("please fill a valid email record you may need it to recover your account.");
NpcHtmlMessage htm = new NpcHtmlMessage(0);
htm.setHtml(HtmCache.getInstance().getHtm(player.getHtmlPrefix(), htmlPath + "createPassword2.htm"));
player.sendPacket(htm);
return false;
}
PlayerSecondPassword.onCreate2(player, pass, email);
}
else
{
NpcHtmlMessage htm = new NpcHtmlMessage(0);
htm.setHtml(HtmCache.getInstance().getHtm(player.getHtmlPrefix(), htmlPath + "createPassword2.htm"));
player.sendPacket(htm);
player.sendMessage("Please fill all of the fields before continuing.");
return false;
}
i always get the return "Please fill all of the fields before continuing"

Username and password exist but not found and authenticated

The password and username are retrieved from the database. If one row is returned, a user exists. However, the below code says that the user does not exist even if the username and password are correct.
if(con != null) {
try {
String query = "select * from users where username = '"+user.getText()+"' and password = '"+pasword.getText()+"'";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
int count = 0;
while(rs.next()) {
count = count + 1;
}
if(count == 1) {
JOptionPane.showMessageDialog(null, "user exist");
} else {
JOptionPane.showMessageDialog(null, "user doesnot exist");
}
rs.close();
ps.close();
} catch (Exception e1) {
}
}
It´s a sensible code, but you should to write the
e.printStackTrace()
in the catch block, maybe an exception it's occurs. Check the user.getText() and password.getText() content, also you can apply an user.getText().trim() for example, to delete de blank spaces. Then try this:
while(rs.next()) {
count++;
}
if(count > 0) {
JOptionPane.showMessageDialog(null, "user exist");
} else {
JOptionPane.showMessageDialog(null, "user doesnot exist");
}
Good luck!

Java -- Why is my authentication program failing to log me in..? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Okay, so I even printed out the values of the variables that will be compared to the username and password.
Username luke
Password: password
Username Attempt: luke
Password Attempt: [C#5e15c325
But I'm attempting to input 'password'.... The JPasswordField holds a character array, so I have to use the 'toCharArray' when comparing the char [] 'passwordAttempt' and the String 'pass' that holds the password that is held in a file. Maybe this is why the password attempt is some strange value?
Here's the code of the login() function:
public void login() {
//booleans for error-handling and user authentication
boolean usersInDatabase = true;
boolean userAuthentication = false;
boolean passwordAuthentication = false;
//create the data reader
try {
reader = new Scanner(user1); //user1 is a file
} catch (FileNotFoundException noUsers) {
JOptionPane.showMessageDialog(window, "No users in the database");
usersInDatabase = false;
}
//variables
String user = ""; //variables that will hold the file data which has the
String pass = ""; //username and password
try {
user = reader.nextLine();
pass = reader.nextLine();
}
//you can skip through the error-handling
catch (NoSuchElementException noUsers) {
JOptionPane.showMessageDialog(window, "No users in the database");
usersInDatabase = false;
}
if (usersInDatabase)
{
String userAttempt = usernameField.getText();
String message = ""; //message to display if authentication is unsuccessful
char[] passwordAttempt = passwordField.getPassword();
//okay -- important stuff
//username authentication
if (userAttempt == user) {
userAuthentication = true;
}
else
message += "Incorrect Username -- ";
//password authentication
if (passwordAttempt == pass.toCharArray()) { //check to see if the input matches the string (a character array) that has the value of the file
passwordAuthentication = true;
}
else
message += "Incorrect Password";
if (passwordAuthentication == true && userAuthentication == true)
{
JOptionPane.showMessageDialog(window, "Authorization Successful");
cards.show(cardPanel, "documents");
}
else if(passwordAuthentication == false && userAuthentication == false)
JOptionPane.showMessageDialog(window, message);
//to print out the values for debugging
System.out.println("Username " + user + "\nPassword: " + pass + "\nUsername Attempt: " + userAttempt + "\nPassword Attempt: " + passwordAttempt);
}
}
passwordAttempt == pass.toCharArray()
You cannot compare arrays like this in Java.
Use
Arrays.equals(passwordAttempt, pass.toCharArray());
Or convert them to Strings and compare those (also not by using ==!)
passwordAttemptString.equals(pass);

Categories