Email validation – java code

This is a java method to validate the email address. I used this application in struts (J2EE).
We can also use it in jsp, with little bit modification.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator
{
public boolean eMail(String email)
{
String at=”@”;
String dot=”.”;
int lat=email.indexOf(at);
int lstr=email.length();
Pattern p = Pattern.compile(“.+@.+\\.[a-z]+”);

Matcher m = p.matcher(email);
boolean matchFound = m.matches();

// check if ‘.’ is at the first position or at last position or absent in given email
if (email.indexOf(dot)==-1 || email.indexOf(dot)==0 ||
email.indexOf(dot)==lstr)
{
matchFound =false;
return matchFound;
}

// check if ‘@’ is used more than one times in given email
if (email.indexOf(at,(lat+1))!=-1)
{
matchFound =false;
return matchFound;
}

// check for the position of ‘.’
if (email.substring(lat-1,lat)==dot ||email.substring(lat+1,lat+2)==dot)
{
matchFound =false;
return matchFound;
}

// check if ‘.’ is present after two characters from location of ‘@’
if (email.indexOf(dot,(lat+2))==-1)
{
matchFound =false;
return matchFound;
}

// check for blank spaces in given email
if (email.indexOf(” “)!=-1)
{
matchFound =false;
return matchFound;
}
return matchFound;
}
}

Here I took a boolean value to get the result. If my result is false then I am generating the one message(email is not valid).

If my result is true, then action will happens.

//referred by roseindia.net

Leave a comment