I'm trying to use a while loop for email validation in JFrame (An email has to have "@" and "com" in it). So far I have:
while(!emailInput.getText().matches(".*[@com].*")) {
if (emailInput.getText().matches(".*[@com].*")) {
break;
} //from if
}
if((!emailInput.getText().matches(".*[@com].*"))) {
JOptionPane.showMessageDialog(null, "Your email does not seem to be valid. It should be in the form of myemail@myemail.com. Please try again!");
}
Of course, the while run will be an infinite one - once I tested the program by entering a random email (say, "test"), the condition will always be false. I dare not to put show the dialog (saying that the email doesn't seem right) in the while loop because it will also show the message infinite number of times.
But that is a little bit counterintuitive - since I want the user to keep entering the email until he gets it right (break in while loop).
I have tried to use only if
statement but it seems that my if
code only works once - so I'm counting on while loop. However, is there any way to fix this, even without using while loop? I am using this for password validation and I am having trouble as well. I am open to any suggestion.