Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 855
user3260589 Avatar asked Oct 13 '25 06:10

user3260589


2 Answers

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)) {}
like image 117
Paul Samsotha Avatar answered Oct 14 '25 21:10

Paul Samsotha


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {   
    String email = txtEmail.getText();
    if (!email.contains("@")) {
        jOptionPane1.showMessageDialog(null, "Please"); 
    }
}
like image 41
SimonPJ Avatar answered Oct 14 '25 21:10

SimonPJ