Solved

How to validate an Email Address with plain Java?

Posted on 2006-06-13
19
290 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
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
 

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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
eclipse shortcuts 9 54
print map entry 34 67
table example 4 29
Way to decrease size of apk file 9 65
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)
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

776 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