Link to home
Start Free TrialLog in
Avatar of _Esam
_Esam

asked on

How to validate an Email Address with plain Java?

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
Avatar of StillUnAware
StillUnAware
Flag of Lithuania image

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/)
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)
Avatar of Mayank S
Sorry I didn't realize there was link in between that long code sample.
Avatar of _Esam
_Esam

ASKER

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
Avatar of _Esam

ASKER

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
>> a@com

No.
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-]+)+$"
Avatar of _Esam

ASKER

>"^[_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....
Avatar of _Esam

ASKER

Is this ok: "m-.a@com.m.m.m" ?

_Esam.
>> m-.a@com.m.m.m

Yes that looks ok.
Avatar of _Esam

ASKER

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...
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.
Avatar of _Esam

ASKER

>>   ^[_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
   
Avatar of _Esam

ASKER

Hello....  StillUnAware or mayankeagle

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


Thanks.
_Esam.
ASKER CERTIFIED SOLUTION
Avatar of StillUnAware
StillUnAware
Flag of Lithuania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Avatar of _Esam

ASKER

Excellent .. thanks..
I will look onto the useful links you provided...

Thanks much,...

_Esam.