What's a good technique for validating an e-mail address (e.g. from a user input field) in Android? org.apache.commons.validator.routines.EmailValidator doesn't seem to be available. Are there any other libraries doing this which are included in Android already or would I have to use RegExp?
35 Answers
Another option is the built in Patterns starting with API Level 8:
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
OR
One line solution from @AdamvandenHoven:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
-
32+1 , but i prefer replace the
(target == null)
withTextUtils.isEmpty(target)
:)– HoucineCommented Dec 16, 2013 at 17:40 -
42Answers like these are why I dislike accepted answers being shown on top, instead of answers with most votes.– JeshurunCommented Jan 12, 2014 at 19:58
-
13Would it also not make more sense (readability wise) to simply combine this into one line: return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); Commented Apr 17, 2014 at 16:35
-
1@Houcine, true but the method above returns boolean so we don't have that information when it is false. Anyway, one can toast or update ui from inside the function(must be run in UI thread). For those like me, who are validating an email obtained programmatically and with no user interaction whatsoever, we can just stick with '== null' and maybe save a couple of clock cycles in most cases.– A.J.Commented Dec 28, 2014 at 11:52
-
3Be careful. This matcher accepts
[email protected]
as a valid email Commented Feb 9, 2017 at 17:18
Next pattern is used in K-9 mail:
public static 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}" +
")+"
);
You can use function
private boolean checkEmail(String email) {
return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}
-
79
-
10
-
this helped me a lot thanks and +1 for the simple answer.. :)– DeepthiCommented Feb 11, 2013 at 10:04
-
1FYI: inside character classes the metacharacters much fewer and the hyphen is automatically escaped when put at a border, you can simplify the first class to
[a-zA-Z0-9+._%-]
and the others to[a-zA-Z0-9-]
– RobinCommented Sep 3, 2014 at 10:57 -
This only return true if the email syntax is the same as email does, I tried to remove
i
from@gmail.com
it will return true. Same in `@yaho.com . Commented Sep 25, 2016 at 8:14
Since API 8 (android 2.2) there is a pattern: android.util.Patterns.EMAIL_ADDRESS http://developer.android.com/reference/android/util/Patterns.html
So you can use it to validate yourEmailString:
private boolean isValidEmail(String email) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(email).matches();
}
returns true if the email is valid
UPD: This pattern source code is:
public static final Pattern EMAIL_ADDRESS
= 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}" +
")+"
);
So you can build it yourself for compatibility with API < 8.
-
1
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]"
Why did they repeat'+'
twice? Commented May 19, 2022 at 3:34
We have a simple Email pattern matcher now.
Java:
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Kotlin Function:
private fun isValidEmail(email: String): Boolean {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
Kotlin Extension:
fun String.isValidEmail() =
!TextUtils.isEmpty(this) && Patterns.EMAIL_ADDRESS.matcher(this).matches()
Don't use a reg-ex.
Apparently the following is a reg-ex that correctly validates most e-mails addresses that conform to RFC 2822, (and will still fail on things like "[email protected]", as will org.apache.commons.validator.routines.EmailValidator)
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Possibly the easiest way to validate an e-mail to just send a confirmation e-mail to the address provided and it it bounces then it's not valid.
If you want to perform some basic checks you could just check that it's in the form *@*
If you have some business logic specific validation then you could perform that using a regex, e.g. must be a gmail.com account or something.
-
5I know this answer is about two years old, but when I try this regex using regexr.com, it validates
[email protected]
, and even longer tlds like .museum. Am I missing something? I don't want to block any of my users by failing to validate their valid e-mail address, but this seems to be working for anything I can think of.– Bob VorkCommented Oct 25, 2011 at 7:55 -
@Bob validate Email Address on the server.. check foursquare app it does the same Commented Oct 29, 2011 at 20:18
-
144I'm a bit confused why you start this answer with "Don't use a reg-ex" and then proceed to provide a reg-ex.– howettlCommented Aug 1, 2013 at 19:21
-
9Please keep reading. A better solution is below which does not use regex.– loeschgCommented Jan 27, 2014 at 23:10
-
2@Glen . Would this hold true for Android's Pattern. EMAIL_ADDRESS ? developer.android.com/reference/android/util/… Commented Jul 19, 2018 at 10:32
Use simple one line code for email Validation
public static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
use like...
if (!isValidEmail(yourEdittext.getText().toString()) {
Toast.makeText(context, "your email is not valid", 2000).show();
}
You could write a Kotlin extension like this:
fun String.isValidEmail() =
isNotEmpty() && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
And then call it like this:
email.isValidEmail()
-
1
-
-
This is Android Studio suggestions:
public static boolean isEmailValid(String email) {
return !(email == null || TextUtils.isEmpty(email)) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
-
1null check
email == null
is redandunt as TextUtils checks it inside Commented Apr 6, 2017 at 19:40 -
@VolodymyrKhodonovych you're right, but the null check is done in a OR state, not doing this could lead to a NPE when passing email to the matcher() method.– LampioneCommented Apr 7, 2017 at 11:45
use android:inputType="textEmailAddress" as below:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="email"
android:inputType="textEmailAddress"
android:id="@+id/email"
/>
and:
boolean isEmailValid(CharSequence email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email)
.matches();
}
You can use regular expression to do so. Something like the following.
Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
String email = "[email protected]";
Matcher matcher = pattern.matcher(email);
boolean matchFound = matcher.matches();
Note: Check the regular expression given above, don't use it as it is.
-
3This fails on the following valid email address:
"Example Guy" <[email protected]>
. While you technically can validate email with a regex, it's a little absurd to do so. Commented Aug 18, 2011 at 20:12 -
1
-
1This also matches "guy@@example. com" (not unexpected for users to press the same key twice and some keyboards add a space after a period). This also doesn't support unicode characters. Here are examples of unusual yet valid addresses: en.wikipedia.org/wiki/International_email– tiktakCommented Apr 11, 2022 at 10:03
There is a Patterns
class in package android.util
which is beneficial here. Below is the method I always use for validating email and many other stuffs
private boolean isEmailValid(String email) {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Simplest Kotlin solution using extension functions:
fun String.isEmailValid() =
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}" +
")+"
).matcher(this).matches()
and then you can validate like this:
"[email protected]".isEmailValid()
If you are in kotlin-multiplatform without access to Pattern
, this is the equivalent:
fun String.isValidEmail() = Regex(emailRegexStr).matches(this)
-
You just ripped off android.util.Patterns.EMAIL_ADDRESS and claimed it your own?– tiktakCommented Apr 11, 2022 at 10:09
this is the best way in kotlin Useing Extension Function
fun String.isEmailValid(): Boolean {
return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}
-
2No need for TextUtils.isEmpty(this). this.isNotEmpty() is the standard way of testing for non empty strings.– JohannCommented Mar 31, 2022 at 6:36
Call This Method where you want to validate email ID.
public static boolean isValid(String email)
{
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
For an Email validation android provide some InBuilt Pattern.But it only support API level 8 and above.
Here is code for use that pattern to check email validation.
private boolean Email_Validate(String email)
{
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Make sure that after execute this method you should check that if this method return true then you allow to save email and if this method return false then display message that email is "Invalid".
Hope you get your answer, Thanks you.
Can I STRONGLY recommend you don't try to 'validate' email addresses, you'll just get yourself into a lot of work for no good reason.
Just make sure what is entered won't break your own code - e.g. no spaces or illegal characters which might cause an Exception.
Anything else will just cause you a lot of work for minimal return...
-
3When working with subscriptions and payments this is hardly useful advice. If someone forgets their password we must have a way of securely resetting their password to allow them to continue using the service they have paid for. So sometimes it is best that we ensure they are entering a valid e-mail address for their own sake. Commented Feb 7, 2012 at 9:46
-
1Just to be clear about what I said - if someone is intent on entering a fake/wrong address - no amount of validation will stop them.. Checking for silly mistakes like spaces and no '@' etc. is fine - checking anything else is well into 'diminishing returns'...– user834595Commented Dec 16, 2012 at 15:17
-
3The only way to identify a fake email is via sending an email to that email id and check whether u receive an undelivered report... Commented Mar 11, 2013 at 11:01
-
John, many users will not be intent on entering a fake/wrong address, but may enter it incorrectly by accident. So performing a simple check can be very useful and, as shown in mindriot's answer, is not a lot of work. From my experience, most people enter their email addresses correctly, and the few invalid emails most often seem to be down to innocent typo's. Commented Jan 23, 2015 at 10:30
-
If it is important that the user's email works you send a confirmation email. Everything else is nonsense. Commented Jul 4, 2017 at 8:59
public boolean isValidEmail(String email)
{
boolean isValidEmail = false;
String emailExpression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(emailExpression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches())
{
isValidEmail = true;
}
return isValidEmail;
}
Email Validation in Kotlin:
val email = etEmail.text.toString().trim() // get email from user
if(isValidEmail(email)){ // call isValidEmail function and pass email in parameter
// Your email ID is Valid
}else{
// Enter your valid email ID
}
This method is used for checking valid email id formats.
fun isValidEmail(email: CharSequence): Boolean {
var isValid = true
val expression = "^[\\w.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"
val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE)
val matcher = pattern.matcher(email)
if (!matcher.matches()) {
isValid = false
}
return isValid
}
-
matcher.matches()
return a boolean thus you can return it directly without storing it inisValid
Commented Nov 5, 2021 at 21:37 -
Yeah, we can do like that. Thanks for suggestions Commented Nov 6, 2021 at 9:37
-
-
If you are using API 8 or above, you can use the readily available Patterns
class to validate email. Sample code:
public final static boolean isValidEmail(CharSequence target) {
if (target == null)
return false;
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
By chance if you are even supporting API level less than 8, then you can simply copy the Patterns.java
file into your project and reference it. You can get the source code for Patterns.java
from this link
Here is android.util.Patterns.EMAIL_ADDRESS
[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})+
String
will match it if
Start by 1->256 character in (a-z, A-Z, 0-9, +, ., _, %, - , +)
then 1 '@' character
then 1 character in (a-z, A-Z, 0-9)
then 0->64 character in (a-z, A-Z, 0-9, -)
then **ONE OR MORE**
1 '.' character
then 1 character in (a-z, A-Z, 0-9)
then 0->25 character in (a-z, A-Z, 0-9, -)
Example some special match email
[email protected]
[email protected]
[email protected]
You may modify this pattern for your case then validate by
fun isValidEmail(email: String): Boolean {
return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
Try this simple method which can not accept the email address beginning with digits:
boolean checkEmailCorrect(String Email) {
if(signupEmail.length() == 0) {
return false;
}
String pttn = "^\\D.+@.+\\.[a-z]+";
Pattern p = Pattern.compile(pttn);
Matcher m = p.matcher(Email);
if(m.matches()) {
return true;
}
return false;
}
Try this code.. Its really works..
if (!email
.matches("^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"))
{
Toast.makeText(getApplicationContext(), "Email is invalid",
Toast.LENGTH_LONG).show();
return;
}
Following was used by me. However it contains extra characters than normal emails but this was a requirement for me.
public boolean isValidEmail(String inputString) {
String s ="^((?!.*?\.\.)[A-Za-z0-9\.\!\#\$\%\&\'*\+\-\/\=\?\^_`\{\|\}\~]+@[A-Za-z0-9]+[A-Za-z0-9\-\.]+\.[A-Za-z0-9\-\.]+[A-Za-z0-9]+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(inputString);
return matcher.matches();
}
Answer of this question:- Requirement to validate an e-mail address with given points
Explanation-
- (?!.*?..) "Negative Lookhead" to negate 2 consecutive dots.
- [A-Za-z0-9.!#\$\%\&\'*+-/\=\?\^_`{\|}\~]+ Atleast one characters defined. ("\" is used for escaping).
- @ There might be one "@".
- [A-Za-z0-9]+ then atleast one character defined.
- [A-Za-z0-9-.]* Zero or any repetition of character defined.
- [A-Za-z0-9]+ Atleast one char after dot.
The key here is that you want to fully validate the email address. You don’t just want to check it for syntactic correctness, you want to check whether the email address is real.
Two obvious reasons: real users often mis-type their email addresses, and some users may put in fake email addresses. Therefore, you want to do a syntactic check and an existence check.
The best way to do this that I have found on Android is to use the free Cloudmersive Validation API for this.
The code looks like this:
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
EmailApi apiInstance = new EmailApi();
String email = "email_example"; // String | Email address to validate, e.g. \"[email protected]\". The input is a string so be sure to enclose it in double-quotes.
try {
FullEmailValidationResponse result = apiInstance.emailFullValidation(email);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EmailApi#emailFullValidation");
e.printStackTrace();
}
I’m using this in all my apps and it is great because I can validate the email addresses in the UX at the point of entry.
According to Patterns.EMAIL_ADDRESS, this email is correct "[email protected]". So I modified the regex in Patterns.EMAIL_ADDRESS and increased the minimum length for domain. Here is the function for Kotlin:
fun isEmailValid(email: String): Boolean =
email.isNotEmpty() && 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\\-]{1,25}" +
")+"
).matcher(email).matches()
I just changed domain part from {0,25} to {1,25}.
-
1Technically a 1 letter top level domain could be introduced. It is legal per RFC-952.– tiktakCommented Apr 11, 2022 at 10:07
-
I think you would need to change it to
{2,25}
if you really wanted to ensure the minimum domain length is 2 Commented Jan 2 at 19:41
Note that most of the regular expressions are not valid for international domain names (IDN) and new top level domains like .mobi or .info (if you check for country codes or .org, .com, .gov and so on).
A valid check should separate the local part (before the at-sign) and the domain part. You should also consider the max length of the local part and domain (in sum 255 chars including the at-sign).
The best approach is to transform the address in an IDN compatible format (if required), validate the local part (RFC), check the length of the address and the check the availability of the domain (DNS MX lookup) or simply send an email.
The Linkify class has some pretty useful helper methods that might be relevant, including regular expressions designed to pick up phone numbers and email addresses and such:
http://developer.android.com/reference/android/text/util/Linkify.html
I have used follwing code.This works grate.I hope this will help you.
if (validMail(yourEmailString)){
//do your stuf
}else{
//email is not valid.
}
and use follwing method.This returns true if email is valid.
private boolean validMail(String yourEmailString) {
Pattern emailPattern = Pattern.compile(".+@.+\\.[a-z]+");
Matcher emailMatcher = emailPattern.matcher(emailstring);
return emailMatcher.matches();
}
email is your email-is.
public boolean validateEmail(String email) {
Pattern pattern;
Matcher matcher;
String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
For regex lovers, the very best (e.g. consistant with RFC 822) email's pattern I ever found since now is the following (before PHP supplied filters). I guess it's easy to translate this into Java - for those playing with API < 8 :
private static function email_regex_pattern() {
// Source: http://www.iamcal.com/publish/articles/php/parsing_email
$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
$quoted_pair = '\\x5c[\\x00-\\x7f]';
$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
$domain_ref = $atom;
$sub_domain = "($domain_ref|$domain_literal)";
$word = "($atom|$quoted_string)";
$domain = "$sub_domain(\\x2e$sub_domain)*";
$local_part = "$word(\\x2e$word)*";
$pattern = "!^$local_part\\x40$domain$!";
return $pattern ;
}
if(!Patterns.EMAIL_ADDRESS.matcher(editTextEmail.getText().toString()).matches()){ //show toast:enter valid email }