mindfreak
mindfreak

Reputation: 455

Email validation in Java without using regular expression

I understand that validating email with Regex would have just been a matter of 3-4 lines of code. However, I'm looking to validate email without using Regex. To an extent, the code successfully passes almost all the validations, however, still unable to figure out - how special characters can be avoided being the first & last character of the email address.

List of specialChars = {'!', '#', '$', '%', '^', '&', '*', '(', ')', '-', '/', '~', '[', ']'} ;

What I am looking at is:

If the username section (abc.xyz@gmail.com) starts or ends with any of the special characters, it should trigger an "Invalid email address" error. The same goes with domain section as well.

For eg... the following list of email-IDs should print an "Invalid email ID" error message

#[email protected]

abc.xyz&@gmail.com

abc.xyz&@!gmail.com

abc.xyz&@gmail.com!

import java.util.Scanner;

public class Email_Validation {

    public static void main(String[] args) {

        // User-input code
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter your email address");
        String email = scan.next();

        // Code to check if email ends with '.' (period sign) 
        boolean checkEndDot  = false;
        checkEndDot = email.endsWith(".");

        // Code to find out last index of '@' sign
        int indexOfAt = email.indexOf('@');
        int lastIndexOfAt = email.lastIndexOf('.');


        //Code to check occurence of @ in the email address  
        int countOfAt = 0;

        for (int i = 0; i < email.length(); i++) {
            if(email.charAt(i)=='@')
                countOfAt++; }


        // Code to check occurence of [period sign i..e, "."] after @ 
        String buffering = email.substring(email.indexOf('@')+1, email.length());
        int len = buffering.length();

        int countOfDotAfterAt = 0;
        for (int i=0; i < len; i++) {
            if(buffering.charAt(i)=='.')
                countOfDotAfterAt++; }


// Code to print userName & domainName
            String userName = email.substring(0, email.indexOf('@'));
            String domainName = email.substring(email.indexOf('@')+1, email.length());

                System.out.println("\n");   

               if ((countOfAt==1) && (userName.endsWith(".")==false)  && (countOfDotAfterAt ==1) &&   
                  ((indexOfAt+3) <= (lastIndexOfAt) && !checkEndDot)) {

                   System.out.println("\"Valid email address\"");}

               else {       
                        System.out.println("\n\"Invalid email address\""); }


                System.out.println("\n");
                System.out.println("User name: " +userName+ "\n" + "Domain name: " +domainName);


    }
}

How do I get this resolved ?

Upvotes: 0

Views: 20749

Answers (4)

Sonthosh B
Sonthosh B

Reputation: 11

Check the below code, I believe it satisfies your email validation.

Apache common lang maven dependency.

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

Java email validation utility code.

public class EmailValidationUtility {


    private static final String[] SPECIAL_CHARACTERS_FOR_USERNAME = new String[] {
                "..", "__", ",", "/", "<", ">", "?", ";", ":", "\"", "\"",
                "{", "}", "[", "]", "|", "\\", "!", "@", "#", "$", "%", "^",
                "&", "*", "(", ")", "+", "=", "~", "`" };

    private static final char[] SPECIAL_CHARACTERS_WITH_NUMBERS = new char[] {
                '.', ',', '/', '<', '>', '?', ';', ':', '\'', '\"', '{',
                '}', '[', ']', '|', '\\', '!', '@', '#', '$', '%', '^', '&',
                '*', '(', ')', '-', '_', '+', '=', '~', '`', '1', '2', '3',
                '4', '5', '6', '7', '8', '9', '0' };

    /**
     * Method to validate the input email is valid or not.
     *
     * @param email the email
     * @return true, if is email valid
     */
    public static boolean isEmailValid(String email) {
        String[] emailChunks = StringUtils
                        .splitByWholeSeparatorPreserveAllTokens(email,
                                        "@");

        if (emailChunks.length != 2 || isEmailUserNameInvalid(emailChunks[0])
                        || StringUtils.isBlank(emailChunks[1])) {
            return false;
        }

        String[] domainNames = StringUtils
                        .splitByWholeSeparatorPreserveAllTokens(emailChunks[1],
                                        ".");
        if (domainNames.length < 2) {
            return false;
        }

        int topLevelDomainNameIndex = domainNames.length - 1;
        if (isTopLevelDomainNameInvalid(domainNames[topLevelDomainNameIndex])) {
            return false;
        }

        domainNames = ArrayUtils.remove(domainNames, topLevelDomainNameIndex);

        return (isDomainNameValid(domainNames));
    }



    private static boolean isEmailUserNameInvalid(String emailUserName) {
        return (StringUtils.isBlank(emailUserName) || StringUtils.containsAny(
                        emailUserName, SPECIAL_CHARACTERS_FOR_USERNAME));
    }


    private static boolean isTopLevelDomainNameInvalid(String topLevelDomain) {
        return (StringUtils.isBlank(topLevelDomain) || StringUtils.containsAny(
                        topLevelDomain, SPECIAL_CHARACTERS_WITH_NUMBERS));
    }
    
    private static boolean isDomainNameValid(String[] domainNames) {
        for (String domainName : domainNames) {
            if ((StringUtils.isBlank(domainName) || StringUtils.containsAny(
                            domainName, SPECIAL_CHARACTERS_WITH_NUMBERS))) {
                return false;
            }
        }
        return true;
    }
}

Upvotes: 0

Georgios Syngouroglou
Georgios Syngouroglou

Reputation: 20024

I use EmailValidator from the Apache Commons library.
An example above,

String email = "[email protected]";
EmailValidator validator = EmailValidator.getInstance();
if (!validator.isValid(email)) {
   // The email is not valid.
}

or

if (!EmailValidator.getInstance().isValid("[email protected]")) {
   // The email is not valid.
}

If you are using maven then you can use this dependency,

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.4.0</version>
    <type>jar</type>
</dependency>

Upvotes: 1

kg_sYy
kg_sYy

Reputation: 1215

How about this:

public class EmailMe {
  private static Set<Character> bad = new HashSet<>();

  public static void main(String[] args) {
    char[] specialChars = new char[] {'!', '#', '$', '%', '^', '&', '*', '(', ')', '-', '/', '~', '[', ']'} ;
    for (char c : specialChars) {
      bad.add(c);
    }
    check("#[email protected]");
    check("abc.xyz&@gmail.com");
    check("abc.xyz&@!gmail.com");
    check("abc.xyz&@gmail.com!");
  }

  public static void check(String email) {
    String name = email.substring(0, email.indexOf('@'));
    String domain = email.substring(email.indexOf('@')+1, email.length());
//    String[] split = email.split("@");
    checkAgain(name);
    checkAgain(domain);
  }


  public static void checkAgain(String part) {
    if (bad.contains(part.charAt(0))) System.out.println("bad start:"+part);
    if (bad.contains(part.charAt(part.length()-1))) System.out.println("bad end:"+part);
  }
}

Upvotes: 2

Dean J
Dean J

Reputation: 40369

So, take a look at the String API. http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Specifically, you've got String.length(), and String.charAt(). So you can get the first and last characters from the String very, very easily. You do this in your code at one point already; assuming you've got it.

You could run through a long if statement here;

char first = email.charAt(0);
if (first == '!' || first == '#' || <more here>) { 
    return false;
}

But that could be a headache. Another way to do this would be to use a Set, which is more efficient if you need to check this many times. (Lookup into a HashSet is generally pretty quick.) You'd create the set once, then be able to use it many times with Set.contains(first), for example.

Upvotes: 1

Related Questions