How to check email from JTextField

As in the title, I want to display jOptionPane if there is no specific character in jTextField. Let's say that the symbol 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 cannot get this to work. I also tried using contains()and contentEquals(), but I do not know how to use it correctly, so I changed the code. A Google search also does not help, because I cannot find what I want. Please think of help. By the way, I use netbeans.

+3
source share
2 answers

If you are trying to check your email, use String.matches(regex)

. .

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)) {}
+3
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {   
    String email = txtEmail.getText();
    if (!email.contains("@")) {
        jOptionPane1.showMessageDialog(null, "Please"); 
    }
}
+3

All Articles