While loop for email validation in Java JFrame
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 [email protected]. 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.
As Sebastian suggested, the solution is to use a button, get rid of the while
loop, and just use an if
statement. The reason is that if the user clicks on it, the program would have checked the validation - and it checks the validation whenever the user clicks on the button. The process ends when the user enters a valid email and clicks on the button for the final time.