As mentioned by @JeroenVannevel, there really isn't a good way to do this. The best you can do is something like this:the below. Essentially, I have one function, isEmailAddress
, which returns true
if an @
character is found in the email address.
import javax.swing.JOptionPane;
public class MailTest {
public boolean isEmailAddress(String emailAddress) {
return emailAddress.contains("@");
}
public static void main(String[] args) {
String emailAddress = JOptionPane.showInputDialog("Enter an email address.")
if(isEmailAddress(emailAddress)) {
System.out.println("What a correct email!");
}
}
}
As, again mentioned by @JeroenVannevel, there are just too many issues to consider when trying to validate email addresses, here are just a few of those issues:
- An email address doesn't necessarily, end with a domain name, i.e,
foo.bar
. - An email address can contain an IP address as a domain name, i.e,
3.3.4.2
, or others. - An email address can also have different formats as well.
In short, the only "good" way to check if an email address is valid is to ensure that it contains an @
character.