Search code examples
javaloopsemail-validation

Email validation using java program


I am writing a java program on email validation.

The code must not contain:

  • built-in functions (aside from String methods and the like)
  • regular expressions

The code must contain:

  • loops
  • collections

I understand that email validation is harder without the use of regular expressions, but this question has been asked in an interview.

Are there any possibilities to write such a code or any alternate methods?


Solution

  • Use something like this :

    public class EmailValidation {
        public static void main(String[] args) {
            String email = "SAMPLE_EMAIL";
    
            String[] deniedIdCharList = { ",", ";", "'", "\"", "[", "]", "|", "\\",
                     "=",  "!", "#", "$", "%", "^", "&", "*", "(", ")",
                    "/", "`", "~", ":", "<", ">", "?", "{", "}" };
    
            int atLoc = email.indexOf("@");
            if (atLoc == -1) {
                System.out.println("fail");
            } else {
                String id = email.substring(0, atLoc);
                String domain = email.substring(atLoc + 1, email.length());
    
                if (domain.indexOf("@") != -1) {
                    System.out.println("fail");
                }
    
                else {
    
                    for (String deny : deniedIdCharList) {
                        if (id.indexOf(deny) != -1) {
                            System.out.println("fails");
                        }
                        if (domain.indexOf(deny) != -1) {
                            System.out.println("fails");
                        }
    
                    }
                    if (id.length() == 0 || domain.length() == 0) {
                        System.out.println("fails");
                    }
    
                    int dotIndex = domain.indexOf(".");
                    String host = domain.substring(0, dotIndex);
                    String extn = domain.substring(dotIndex + 1);
                    if (host.length() == 0) {
                        System.out.println("fail");
                    }
                    if ((extn.length() != 2 && extn.length() != 3 && extn.length() != 5)) {
                        System.out.println("fail");
                    }
                    if (extn.length() == 5 && extn.indexOf(".") == -1) {
                        System.out.println("fail");
                    }
    
                }
    
            }
    
        }
    }
    

    This worked for most standard checks I subjected it to. The code can be improved (A LOT) in terms of efficiency, however my guess is this is more from a "Can it be done" or Academic point of view rather than usage perspective. If you plan to use this methodology I advise strongly against it and refer to the answer provided by @vikeng21