Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to validate an Email Address with plain Java?

Posted on 2006-06-13
19
Medium Priority
?
307 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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 500 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
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:
Suggested Courses

715 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