Solved

How to validate an Email Address with plain Java?

Posted on 2006-06-13
19
287 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:mayankeagle
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:mayankeagle
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:mayankeagle
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

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:mayankeagle
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

705 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

18 Experts available now in Live!

Get 1:1 Help Now