public static void main(String[] args) {
System.out.println(vaidateEmailAddress("exa.mple@gmail.com") );
System.out.println(vaidateEmailAddress("exa..mple@gmail.com") );
}
static boolean vaidateEmailAddress(String email){
boolean valid = false;
String domain[] = {"gmail.com" , "yahoo.com", "hotmail.com" };
String localPart = email.substring(0, email.indexOf('@', 0));
String domainPart = email.substring( localPart.length() + 1, email.length());
int noOfAts = 0;
for(int i = 0 ; i < email.length(); i++){
if( email.indexOf('@', i) != -1){
noOfAts++;
i = email.indexOf('@', i);
}
}
if(noOfAts > 1 || noOfAts == 0) {
// if more than one @ symbol appears no point in further checking. Its a invalid email address
return false;
}
else{
// now that it has been found that there is only one @ symbol lets check the domain
for( int i = 0 ; i < domain.length ; i++){
if( domainPart.equals(domain[i])){
valid = true;
// still further processing of the string is needed. Thats why it doesn't return true
}
}
}
// checks for the presence of invalid characters in the local part
if(localPart.charAt(0) == '.' || localPart.charAt(localPart.length() -1) == '.'){
return false;
}
else{
for(int i =0 ; i < email.indexOf('@', 0); i++){
if(validCharacter(email.charAt(i)) ){
}
else if(email.charAt(i)== '.' && email.charAt(i+1)== '.'){
return false;
}
else if(email.charAt(i)=='.'){
}
else{
return false;
}
}
}
return valid;
}
static boolean validCharacter(char c){
char validSymbols[] = {'!', '#' ,'$' ,'%' ,'&' ,'\'' ,'*' ,'+', '-', '/', '=' ,'?', '^','_','`' ,'{' ,'|' ,'}', '~'};
for(int i =0 ; i < validSymbols.length; i++){
if(validSymbols[i] == c ){
}
else{
if(Character.isLetter(c)){
}
else if(Character.isDigit(c)){
}
else{
return false;
}
}
}
return true;
}
}
Tuesday, June 14, 2011
Validate a email address in java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment