Search code examples
javaswingvalidationjtextfieldjoptionpane

How to validate an email from JTextField


Just like the title says, I want to display a jOptionPane if there's a missing specific character in a jTextField. Let's say that character is "@".

I tried something like this:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {   
   String email = (String)txtEmail.getText();
   if (!email.equals(email) && email.equals("@")){
      jOptionPane1.showMessageDialog(null, "Please"); 
   }
}

However, I can't get this to work. I also tried using contains() and contentEquals() but I don't know how to use it properly so I had changed the code. Searching on Google also doesn't help because I can't find what I want. Please consider helping. BTW, I'm using netbeans.


Solution

  • If you're trying to validate an email, use String.matches(regex)

    Here is an imlementation of the email regex validation patter from this site. An explanation of the regex can also be found on the site.

    private static final String EMAIL_PATTERN = 
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    
    if (!email.matches(EMAIL_PATTERN)) {}