Solved

How to validate an Email Address with plain Java?

Posted on 2006-06-13
19
289 Views
Last Modified: 2012-06-27
Hi,
I have some records that I am storing in a bean like class.
email address is one of the variable within this class.
I want to have a method that takes a string (the email) and validates the email address.
Need some logic to validate the email address...
Thanks.
_Esam
0
Comment
Question by:_Esam
  • 8
  • 7
  • 4
19 Comments
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16894779
Some possible solutions:

      //Input the string for validation
      String email = "xyz@hotmail.com";

      //Set the email pattern string
      Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

      //Match the given string with the pattern
      Matcher m = p.matcher(email);

      //check whether match is found
      boolean matchFound = m.matches();

      if (matchFound)
        System.out.println("Valid Email Id.");
      else
        System.out.println("Invalid Email Id.");
from (http://www.devx.com/tips/Tip/28334)

/*
* Checks for invalid characters
* in email addresses
*/
public class EmailValidation {
   public static void main(String[] args)
                                 throws Exception {
                                 
      String input = "@sun.com";
      //Checks for email addresses starting with
      //inappropriate symbols like dots or @ signs.
      Pattern p = Pattern.compile("^\\.|^\\@");
      Matcher m = p.matcher(input);
      if (m.find())
         System.err.println("Email addresses don't start" +
                            " with dots or @ signs.");
      //Checks for email addresses that start with
      //www. and prints a message if it does.
      p = Pattern.compile("^www\\.");
      m = p.matcher(input);
      if (m.find()) {
        System.out.println("Email addresses don't start" +
                " with \"www.\", only web pages do.");
      }
      p = Pattern.compile("[^A-Za-z0-9\\.\\@_\\-~#]+");
      m = p.matcher(input);
      StringBuffer sb = new StringBuffer();
      boolean result = m.find();
      boolean deletedIllegalChars = false;

      while(result) {
         deletedIllegalChars = true;
         m.appendReplacement(sb, "");
         result = m.find();
      }

      // Add the last segment of input to the new String
      m.appendTail(sb);

      input = sb.toString();

      if (deletedIllegalChars) {
         System.out.println("It contained incorrect characters" +
                           " , such as spaces or commas.");
      }
   }
}

from (http://java.sun.com/developer/technicalArticles/releases/1.4regex/)
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16894831
This looks promissing:

"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*$"

it provides somewhat more accurate regex expression
from (http://www.h2co3.com/blog/archives/000013.html)
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16894869
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16894903
> http://www.devx.com/tips/Tip/28334

Already posted that :)
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16894934
Sorry I didn't realize there was link in between that long code sample.
0
 

Author Comment

by:_Esam
ID: 16895055
NOW..
> "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*$"

Should this be enough to validate an email address/

_Esam
0
 

Author Comment

by:_Esam
ID: 16895243
Is this a valid email address: "a@com"  ?
This > "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*$"
returns this email address as valid???

_Esam
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16895285
>> a@com

No.
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16895327
Instead of

"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*$"

use this

"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$"
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:_Esam
ID: 16895380
>"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$"

I personally don't think that this is enough :)
What do you say???
_Esam....
0
 

Author Comment

by:_Esam
ID: 16895398
Is this ok: "m-.a@com.m.m.m" ?

_Esam.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16895514
>> m-.a@com.m.m.m

Yes that looks ok.
0
 

Author Comment

by:_Esam
ID: 16895791
I have the method as:

public static boolean isValidEmailAddress(String email)
    {
        String regex = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$" ;
        return email.matches(regex);
    }

Now, I looked at this link: http://java.sun.com/developer/technicalArticles/releases/1.4regex/

And I think I should include some other conditions too....

Not quite sure how to do that...
I want to test the email for all the conditions and then return if true...

How?

Thanks.
_Esam...
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16895884
It won't give You any better results. The regex You are using is one of many solutions, here is another one
(from http://www.houseoffusion.com/cf_lists/messages.cfm/forumid:21/threadid:149):

^[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.(([0-9]{ 1,3})|([a-zA-Z]{2,6})

The last one is a little bit more restrictive and accurate, but still not perfect, cause it's not possible to be sure if the text You are reading is some 'text', email address or simply trash.

To be convinced on that, try for example use OutlookExpress, add some news group and try to open a message with partial file attachment. The OutlookExpress starts to filter the binary data for links, which results in heavy time consuming and meaningless task.
0
 

Author Comment

by:_Esam
ID: 16895972
>>   ^[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.(([0-9]   (here) { 1,3})|([a-zA-Z]{2,6})

It gave me some error here --- the white space  

The error: (the by ^)
java.util.regex.PatternSyntaxException: Illegal repetition near index 74
^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]     ^         { 1,3})|([a-zA-Z]{2,6})

Let me know..
Thanks.
_Esam
   
0
 

Author Comment

by:_Esam
ID: 16896533
Hello....  StillUnAware or mayankeagle

What's wrong with the expression... some syntax error...
Can you figure out..
I can't see it...


Thanks.
_Esam.
0
 
LVL 14

Accepted Solution

by:
StillUnAware earned 125 total points
ID: 16897087
Sorry for that, I did a quick copy and edit and missed some last characters. It should be:

"^[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.(([0-9]{1,3})|([a-zA-Z]{2,6}))$"
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16897223
Also, to get a grip on regular expressions may be usefull for future tasks, You should consider reading a bit more about it, at least to understand what does the supplied expressions means. Some info:

http://java.sun.com/docs/books/tutorial/extra/regex/index.html
http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html
0
 

Author Comment

by:_Esam
ID: 16897424
Excellent .. thanks..
I will look onto the useful links you provided...

Thanks much,...

_Esam.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to parse custom JSON to POJO java 4 56
json example 39 132
Java - Why doesn't this JFrame work 3 43
Configure a Bean in an XML file 4 12
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now