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:-)
Hey there..
ReplyDeleteThe 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..:-)
thanks!
ReplyDeleteGood!
ReplyDeletehelped me a lot.
saved my time in learning.
yet i'm learning the trick
Thank u Boss
ReplyDeleteThanks. Best explanation to use regex in Android out there! Really helped me out for my app.
ReplyDeleteif iam using the code of validation of email itz not working
ReplyDeleteHi Sudhakar,
ReplyDeleteAppreciate,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.
public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
ReplyDelete"[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}" +
")+"
);
Hi
ReplyDeleteThe rgexp. is working fine but the problem in second last combination
like ashu@c.com in also a valid mail.