1

The problem statement goes like this:

We need to create a String data type called emailId

The email ID has to be set using appropriate setter methods.

The validation rules for the email ID check have to be implemented in the main().

Conditions are:

  1. Overall length of the email ID must be >3 and <20.

  2. The emailId must include "@" followed by a minimum of 1 and maximum of 2 "." characters.

  3. The substring before "@" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.

  4. The first letter of the email Id must be in Upper Case.

If all the above conditions are valid, it should display "Email ID is valid" or else, it should display an appropriate error message

This is my code:

public class EmailCheck {

String emailId;
public void setEmailId(String emailId){
    this.emailId=emailId;
}
public String getEmailId(){
    return emailId;
}
public static void main(String[] args) {
    EmailCheck em = new EmailCheck();
    em.setEmailId("CFDV@gm.a.il.com");
    String email = em.getEmailId();
    int length = email.length();
    boolean flag1 = false;
    boolean flag2 = false;
    boolean flag3 = false;
    boolean flag4 = false;
    boolean flag5 = false;
    boolean flag6 = false;
    boolean flag7 = false;
    int count = 0;


    //Condition 1 
    if((length>3 && length<20)== true)
        flag1 = true;
    else 
        flag1 = false;

    //Condition 2
        int temp = email.length();
        if(email.contains("@")){
            flag2=true;
            int a=email.indexOf("@");
             for(int i=a;i<temp;i++){
        if(email.charAt(i)=='.'){
        flag3=true; 
        count=count+1;
        }
        }
        if(count<1||count>2){
        flag4=false;
        }
        else{
        flag4=true;
        }
        }
        else{
        flag2 =false;
        System.out.println("No @ symbol present");
        }


    //Condition 3
    if(email.matches("[A-Z a-z _]+@.*")) //Unable to get the right RegEx here!
        flag5 = true;
    else
        flag5 = false;

    //Condition4
    if(Character.isUpperCase(email.charAt(0))==true)
            flag6 = true;
    else
        flag6=false;

    if(flag1==true && flag2==true && flag3==true && flag4==true && flag5==true &&flag6==true)
        System.out.println("Email ID is valid");
    else{
        if(flag1==false)
            System.out.println("Inavlid length of Email ID");
        if(flag2==false||flag3==false||flag4==false)
            System.out.println("Invalid Position of Special Characters");
        if(flag5==false)
            System.out.println("Invalid combination for username");
        if(flag6==false)
            System.out.println("Invalid case of first letter");
    }


}
}

I'm not sure of the condition #2(the logic?) and condition #3(the RegExp part). A few of the test cases seem correct, the rest of them are wrong(owing to faulty logic in #2 and esp #3, I think.)

Please, tell me what changes have to be done here to get the right output. Thanks!

user2377778
  • 75
  • 1
  • 3
  • 6
  • 3
    Every one of your validation rules is wrong. Don't do this. – SLaks May 13 '13 at 14:10
  • Side note: `if((length>3 && length<20)== true)` should be `if(length>3 && length<20)` – Maroun May 13 '13 at 14:10
  • @Slaks Can you please suggest what I should improve on? – user2377778 May 13 '13 at 14:11
  • Wrong is subjective. That could be right under certain circumstances. Sounds like class work though – Kyle May 13 '13 at 14:12
  • 2
    Get rid of them all. The rules for valid email addresses are extremely complicated; you should use http://commons.apache.org/proper/commons-validator/apidocs/org/apache/commons/validator/routines/EmailValidator.html – SLaks May 13 '13 at 14:12
  • http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address?rq=1 – Brian Roach May 13 '13 at 14:13
  • 1
    @Kyle: I can't think of any sane circumstances in which any of the rules would be right. – SLaks May 13 '13 at 14:13
  • @SLaks :( Oh! I will look into it. I'm just a beginner at Java, coding this for a java 101 class, so we've been provided with a few rules to get the grip of programming, that's all. – user2377778 May 13 '13 at 14:14
  • @Kyle : Yes, this is classwork. Basics of Java Programming. – user2377778 May 13 '13 at 14:16
  • this code is so wrong my JVM is crying – aran May 13 '13 at 14:34
  • [A-Z][a-zA-Z_]*(?<=_)(?<=[A-Z])(?<=[a-z])@.{1,2}(?<=.{4,19}) ill throw out a one liner. – Kyle May 13 '13 at 14:35
  • @Kyle All the 4 conditions need not be in the same reg-expression. Just the RegExp for Condition #3 would suffice. – user2377778 May 13 '13 at 14:37

2 Answers2

4

If you insist on using regex you can use this but without validating properly you could be in for all kinds of trouble

static Pattern emailPattern = Pattern.compile("[a-zA-Z0-9[!#$%&'()*+,/\-_\.\"]]+@[a-zA-Z0-9[!#$%&'()*+,/\-_\"]]+\.[a-zA-Z0-9[!#$%&'()*+,/\-_\"\.]]+");

public static boolean isValidEmail(String email) {

    Matcher m = emailPattern.matcher(email); return !m.matches();

}

Or alternatively you could use

public static boolean isValidEmailAddress(String email) {
   boolean result = true;
   try {
      InternetAddress emailAddr = new InternetAddress(email);
      emailAddr.validate();
   } catch (AddressException ex) {
      result = false;
   }
   return result;
}

Which is a core java utility which would be better...

Note that neither of these will guarentee an address is actually valid, just that it is correctly formed and so hypothetically could exist

String email_regex = "[A-Z]+[a-zA-Z_]+@\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
String testString = "Im_an_email@email.co.uk";
Boolean b = testString.matches(email_regex);
System.out.println("String: " + testString + " :Valid = " + b);

will check for the last three constraints which you can then combine with

string.length()>3 && string.length()<20
rcbevans
  • 7,101
  • 4
  • 30
  • 46
  • Maybe you could update your answer with the last example from here http://howtodoinjava.com/regex/java-regex-validate-email-address/ otherwise good explanation you gave there. – Joseph Jan 29 '16 at 12:08
0

Overall length of the email ID must be >3 and <20.

You have this part fine - a pair of length checks. Things to consider:

  1. You don't need if (condition == true), just if (condition).
  2. If this fails, you can stop processing the email and just display the error. The same applies for all your other error conditions.

The emailId must include "@" followed by a minimum of 1 and maximum of 2 "." characters.

Check for the @ sign first and get the index. Once you have that, you can split the string. You can then split the substring on periods and count them - you want two or three.

There's probably a regex that would do this as well.

The substring before "@" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.

You can use this approach to ensure your regex must match each part. As it stands, I believe your regex will work if there are caps, lowercase, or an underscore instead of checking for all three.

The first letter of the email Id must be in Upper Case.

Same comments as for the first part, drop the == true and short circuit the method if it fails.

Community
  • 1
  • 1
thegrinner
  • 11,546
  • 5
  • 41
  • 64