Validating Email address pattern in Android/Java


We use regular expressions along with Pattern & Matcher classes and their methods to validate email address

Required regular expression is  as below:

String regExpn =
"^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
    +"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
      +"[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
      +"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
      +"[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
      +"([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";

Validation code goes as below:

private Boolean isValidEmail(String inputEmail)
{
      Pattern patternObj = Pattern.compile(regExpn);

      Matcher matcherObj = patternObj.matcher(inputEmail/*May be fetched from  EditText. This string is the one which you wanna validate for email*/);
            if (matcherObj.matches())
            {
                  //Valid email id…
                  return true;
}
            Else
{
//not a valid email id…
                  return false;
}
}


Happy coding:-)

9 comments:

  1. Hey there..

    The regular expression which I have mentioned earlier("^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";) was not so efficient enough to validate more accurately..

    I have corrected the regexp (with text font=red)

    Excuse me for correction..:-)

    ReplyDelete
  2. Good!
    helped me a lot.
    saved my time in learning.
    yet i'm learning the trick

    ReplyDelete
  3. Thanks. Best explanation to use regex in Android out there! Really helped me out for my app.

    ReplyDelete
  4. if iam using the code of validation of email itz not working

    ReplyDelete
  5. Hi Sudhakar,

    Appreciate,if you can provide any error-log/crash-log/more-description of the problem you are facing.

    Also, please let me know what you have done and some of test cases which lead you to mal functioning.

    ReplyDelete
  6. public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
    "[a-zA-Z0-9+._%-+]{1,256}" +
    "@" +
    "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" +
    "(" +
    "." +
    "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" +
    ")+"
    );

    ReplyDelete
  7. Hi

    The rgexp. is working fine but the problem in second last combination
    like ashu@c.com in also a valid mail.

    ReplyDelete