370

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?

Sufian
  • 6,405
  • 16
  • 66
  • 120
znq
  • 44,613
  • 41
  • 116
  • 144
  • please refers this one, may it will help you: http://stackoverflow.com/questions/12947620/email-address-validation-in-android-on-edittext – Hiren Patel Apr 15 '13 at 04:48
  • 1
    @user2757064 well this question should help the other question you linked. That question was asked 3 years after this. :) – Sufian Aug 15 '14 at 07:44
  • for simple check: `if(!Patterns.EMAIL_ADDRESS.matcher(editTextEmail.getText().toString()).matches()){ //show toast:enter valid email }` – AG-Developer Dec 02 '22 at 19:08

35 Answers35

1133

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();
  }
}

Patterns viewable source

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();
}
mindriot
  • 14,149
  • 4
  • 29
  • 40
  • 32
    +1 , but i prefer replace the `(target == null)` with `TextUtils.isEmpty(target)` :) – Houcine Dec 16 '13 at 17:40
  • 42
    Answers like these are why I dislike accepted answers being shown on top, instead of answers with most votes. – Jeshurun Jan 12 '14 at 19:58
  • 13
    Would 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(); – Adam van den Hoven Apr 17 '14 at 16:35
  • Updated answer reflecting comments. Thanks to @Houcine and AdamvandenHoven. – mindriot Apr 20 '14 at 20:48
  • @Houcine, can you explain why? – A.J. Dec 23 '14 at 17:53
  • @user1951805 : because the predefined method in the TextUtils class is testing either if the String variable is null , or if it is empty or not , and i think that it checks if it contains only white spaces. that's why i recommand using TextUtils.isEmpty() method. – Houcine Dec 24 '14 at 23:27
  • @Houcine, but aren't the additional checks provided by TextUtils simply redundant in this case? We are matching pattern anyway. – A.J. Dec 26 '14 at 06:51
  • @user1951805 : But you want to display to the user a toast or a message dialog if he lefts the email field empty or just entered white spaces :) – Houcine Dec 27 '14 at 20:55
  • @Houcine, pattern match will return false in those cases. So we'll know input is not a valid email. – A.J. Dec 28 '14 at 03:33
  • @user1951805 : i know :D. but there is a difference if you want to display a toast to the user that the email field is empty, and displaying a message toast to the user that the entered email is not valid. – Houcine Dec 28 '14 at 11:34
  • 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. Dec 28 '14 at 11:52
  • @user1951805 : as you said, it depends on the use case – Houcine Dec 28 '14 at 12:15
  • Those who are using the above code as-is and relying on the boolean returned by isValidEmail may replace TextUtils.isEmpty(target) with target == null and save a few clock cycles in most cases. – A.J. Dec 28 '14 at 12:47
  • Note that the Patterns.EMAIL_ADDRESS is *extremely* liberal in what it allows...basically, it'll check that it's syntactically correct, but that means wejhfwefhewjh@kjhwefkjhewkjfhew.wejhfewjhfjew is "correct." That may or may not be the kind of sanity check you want. – ZaBlanc Jan 20 '16 at 18:47
  • value of android.util.Patterns.EMAIL_ADDRESS itself is null.and match method returns false. – Vikas Pandey Aug 03 '16 at 09:45
  • @ZaBlanc: I googled this question because EMAIL_ADDRESS is far too strict. It disallows `!#$&'*/=?^{|}~"(),:;<>@[\]` (and backtick) wholesale, when those are actually valid in the local part under various conditions. – Mooing Duck Feb 04 '17 at 00:24
  • 3
    Be careful. This matcher accepts `email@111.222.333.44444` as a valid email – Joaquin Iurchuk Feb 09 '17 at 17:18
  • `public static boolean isValidEmail(CharSequence target) { return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); }` – Peter Jun 23 '17 at 09:16
  • NPE when you use `android.util.Patterns.EMAIL_ADDRESS.matcher()` for unit tests – Mark Pazon Jun 22 '18 at 04:30
  • anyone else had problems with validating emails with numbers in the end part? e.g zoo@magic.c8m - for me it returns true.. – ZooMagic Jan 10 '20 at 12:18
  • there's an expanded answer on a very long regex here https://stackoverflow.com/a/26989421/6924990 – ZooMagic Jan 10 '20 at 12:37
  • Patterns.EMAIL_ADDRESS is also created with a [regex pattern](https://android.googlesource.com/platform/frameworks/base/+/81aa097/core/java/android/util/Patterns.java#146) . So for those having nullpointer exception while doing jvm tests either needs to rather do instrumentation tests or use the regex directly(won't recommend, google might improve/change the regex in future) : `val patternInternal = "[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}" + ")+"` – ansh sachdeva Aug 17 '20 at 20:00
108

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();
}
Sergii
  • 1,521
  • 3
  • 24
  • 37
Andrei Buneyeu
  • 6,662
  • 6
  • 35
  • 38
76

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}" +
        ")+"
    );

refer to: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/util/Patterns.java

So you can build it yourself for compatibility with API < 8.

Luten
  • 5,420
  • 4
  • 26
  • 24
70

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()
Salman Nazir
  • 2,759
  • 2
  • 28
  • 42
54

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 "user@gmail.com.nospam", 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.

Community
  • 1
  • 1
Glen
  • 21,816
  • 3
  • 61
  • 76
  • 5
    I know this answer is about two years old, but when I try this regex using regexr.com, it validates `user@gmail.com.nospam`, 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 Vork Oct 25 '11 at 07:55
  • @Bob validate Email Address on the server.. check foursquare app it does the same – Harsha M V Oct 29 '11 at 20:18
  • @Harsha I agree with validation on a server, but in my case that isn't possible. I'm making an app where the user can set a mail address to send e-mails to. It's not a subscription and the user doesn't have an account, so I am not sending any confirmation e-mails on every change of the e-mail address… Right now the user just gets a warning when the regex doesn't agree with the e-mail address, but it's not blocking. I was mostly asking out of curiosity :) – Bob Vork Oct 31 '11 at 14:53
  • 143
    I'm a bit confused why you start this answer with "Don't use a reg-ex" and then proceed to provide a reg-ex. – howettl Aug 01 '13 at 19:21
  • 9
    Please keep reading. A better solution is below which does not use regex. – loeschg Jan 27 '14 at 23:10
  • 2
    @Glen . Would this hold true for Android's **Pattern. EMAIL_ADDRESS** ? https://developer.android.com/reference/android/util/Patterns.html#EMAIL_ADDRESS – zulkarnain shah Jul 19 '18 at 10:32
  • Also, if you want to know if the given domain si valid then you can make dns lookup query to google's dns service. Example: https://dns.google/resolve?name=brosoft.com.ar&type=mx – Nico Aug 17 '21 at 20:05
25

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();
}
Sukhchain Singh
  • 834
  • 1
  • 8
  • 26
Pankaj Talaviya
  • 3,328
  • 28
  • 31
20

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()
Filipe Brito
  • 5,329
  • 5
  • 32
  • 42
Danilo Lemes
  • 2,342
  • 1
  • 14
  • 16
16

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();
}
Lampione
  • 1,622
  • 3
  • 21
  • 39
  • 1
    null check `email == null` is redandunt as TextUtils checks it inside – Volodymyr Apr 06 '17 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. – Lampione Apr 07 '17 at 11:45
12

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();
      }
Victor Odiah
  • 1,061
  • 11
  • 14
11

You can use regular expression to do so. Something like the following.

Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
String email = "xyz@xyzdomain.com";
Matcher matcher = pattern.matcher(email);
boolean matchFound = matcher.matches();

Note: Check the regular expression given above, don't use it as it is.

Mudassir
  • 13,031
  • 8
  • 59
  • 87
  • 3
    This fails on the following valid email address: `"Example Guy" `. While you [technically can validate email with a regex](http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html), it's a little absurd to do so. – Cory Petosky Aug 18 '11 at 20:12
  • 1
    Thats not just an email address though. – Brill Pappin Oct 01 '16 at 12:13
  • This 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: https://en.wikipedia.org/wiki/International_email – tiktak Apr 11 '22 at 10:03
10

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();
}
Jimit Patel
  • 4,265
  • 2
  • 34
  • 58
8

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()
    }
Morpheus
  • 550
  • 1
  • 9
  • 23
  • 2
    No need for TextUtils.isEmpty(this). this.isNotEmpty() is the standard way of testing for non empty strings. – Johann Mar 31 '22 at 06:36
7

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:

"testemail6589@gmail.com".isEmailValid()

If you are in kotlin-multiplatform without access to Pattern, this is the equivalent:

fun String.isValidEmail() = Regex(emailRegexStr).matches(this)
Eric
  • 5,323
  • 6
  • 30
  • 35
Gulzar Bhat
  • 1,255
  • 11
  • 13
6

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;
   }
}
Sumit Sharma
  • 1,847
  • 1
  • 22
  • 25
6

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.

AMI CHARADAVA
  • 303
  • 3
  • 9
5

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...

  • 3
    When 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. – Dean Wild Feb 07 '12 at 09:46
  • 1
    Just 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'... –  Dec 16 '12 at 15:17
  • 3
    The only way to identify a fake email is via sending an email to that email id and check whether u receive an undelivered report... – Sreekanth Karumanaghat Mar 11 '13 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. – ban-geoengineering Jan 23 '15 at 10:30
  • If it is important that the user's email works you send a confirmation email. Everything else is nonsense. – The incredible Jan Jul 04 '17 at 08:59
4
    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;
}
Atif Mahmood
  • 8,882
  • 2
  • 41
  • 44
3

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

Mahendra Liya
  • 12,912
  • 14
  • 88
  • 114
3

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

a@b.c
a+@b-.c
a@b.c.d.e.f.g.h

You may modify this pattern for your case then validate by

fun isValidEmail(email: String): Boolean {
    return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
Linh
  • 57,942
  • 23
  • 262
  • 279
3

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
    }
Tippu Fisal Sheriff
  • 2,177
  • 11
  • 19
2

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;
            }
Jenifer
  • 21
  • 1
2

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-

  1. (?!.*?..) "Negative Lookhead" to negate 2 consecutive dots.
  2. [A-Za-z0-9.!#\$\%\&\'*+-/\=\?\^_`{\|}\~]+ Atleast one characters defined. ("\" is used for escaping).
  3. @ There might be one "@".
  4. [A-Za-z0-9]+ then atleast one character defined.
  5. [A-Za-z0-9-.]* Zero or any repetition of character defined.
  6. [A-Za-z0-9]+ Atleast one char after dot.
Vipin Sharma
  • 594
  • 5
  • 19
2

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. \"support@cloudmersive.com\". 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.

2

According to Patterns.EMAIL_ADDRESS, this email is correct "abc@abc.c". 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}.

Daniyal Javaid
  • 1,426
  • 2
  • 18
  • 32
2

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;
}
Kijewski
  • 25,517
  • 12
  • 101
  • 143
Arman
  • 29
  • 2
1

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();

    }
kyogs
  • 6,766
  • 1
  • 34
  • 50
1

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 ;
}
hornetbzz
  • 9,188
  • 5
  • 36
  • 53
1

You can do any type of validation in android very easily by the oval.jar file. OVal is a pragmatic and extensible general purpose validation framework for any kind of Java objects.

follow this link: http://oval.sourceforge.net/userguide.html

You can downlaod this from here: http://oval.sourceforge.net/userguide.html#download

You can use validation by setting tags in variables

public class Something{

    @NotEmpty  //not empty validation
    @Email     //email validation
    @SerializedName("emailAddress")
    private String emailAddress;
}

   private void checkValidation() {
        Something forgotpass.setEmailAddress(LoginActivity.this.dialog_email.getText().toString());
        Validator validator = new Validator();
        //collect the constraint violations
        List<ConstraintViolation> violations = validator.validate(forgotpass);
        if(violations.size()>0){
            for (ConstraintViolation cv : violations){
                if(cv.getMessage().contains("emailAddress")){
                    dialog_email.setError(ValidationMessage.formattedError(cv.getMessage(), forgotpass));
                }
            }
        }
}
Muhammad Aamir Ali
  • 20,419
  • 10
  • 66
  • 57
1

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.

Thorsten
  • 1
  • 1
1

You could also use

InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();

If the email is not valid it will throw an AddressException.

Unfortunately Android doesn't support jndi-dns, but just to give you an idea of a more powerful email validation, you could use it to validate the email domain. Maybe an Android guru could help and show if there are similar alternatives... An example implementation with "regular" java is available here.

EDIT

I just realized that javax.mail isn't support neither... But this post shows a workaround.

Community
  • 1
  • 1
Bob Rivers
  • 5,261
  • 6
  • 47
  • 59
1

I know that It's very too late, still I will give my answer.

I used this line of code to check the inputted Email format:

!TextUtils.isEmpty(getEmail) && android.util.Patterns.EMAIL_ADDRESS.matcher(getEmail).matches();

The problem is, it will only check for the FORMAT not the SPELLING.

When I entered @gmal.com missing i ,and @yaho.com missing another o . It return true. Since it satisfies the condition for Email Format.

What I did is, I used the code above. Since it will give / return true if the if the user inputted @gmail.com ONLY, no text at the start.

FORMAT CHECKER

check

If I enter this email it will give me: true but the spelling is wrong. In my textInputLayout error

wrongSpelling

EMAIL ADDRESS @yahoo.com , @gmail.com, @outlook.com CHECKER

 //CHECK EMAIL
public boolean checkEmailValidity(AppCompatEditText emailFormat){

    String getEmail = emailFormat.getText().toString();
    boolean getEnd;

    //CHECK STARTING STRING IF THE USER
    //entered @gmail.com / @yahoo.com / @outlook.com only
    boolean getResult = !TextUtils.isEmpty(getEmail) && android.util.Patterns.EMAIL_ADDRESS.matcher(getEmail).matches();

    //CHECK THE EMAIL EXTENSION IF IT ENDS CORRECTLY
    if (getEmail.endsWith("@gmail.com") || getEmail.endsWith("@yahoo.com") || getEmail.endsWith("@outlook.com")){
        getEnd = true;
    }else {
        getEnd = false;
    }

    //TEST THE START AND END
    return (getResult && getEnd);
}

RETURN: false

false

noSpecial

RETURN:true

true

XML:

<android.support.v7.widget.AppCompatEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editTextEmailAddress"
            android:inputType="textEmailAddress|textWebEmailAddress"
            android:cursorVisible="true"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:singleLine="true"
            android:maxLength="50"
            android:theme="@style/EditTextCustom"/>

Note: I tried to get the value from EditText and used split on it and even StringTokenizer. Both return false to me.

RoCkDevstack
  • 3,517
  • 7
  • 34
  • 56
  • Why is this response downvoted? it really doesn't work? – Omaraf Sep 28 '16 at 21:16
  • @Omaraf - Try for yourself. You only need to copy the code above. Call this method and pass your password editText. The reason why I didn't test the `editText.startsWith(" ")`, coz it will take `@` as a first character. And `TextUtils` will test for special characters inputted. – RoCkDevstack Sep 29 '16 at 04:42
  • 1
    because it makes assumptions that it shouldn't. the input is not the place to be testing the domain (thats was confirmation email is for), unless of course you are limiting your input to a specific domain of course. – Brill Pappin Oct 01 '16 at 12:17
  • Domain check as implemented here makes no sense at all. – The incredible Jan Jul 04 '17 at 09:03
1

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

Andrew Wyld
  • 7,133
  • 7
  • 54
  • 96
1

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();
}
Umesh
  • 1,609
  • 1
  • 17
  • 28
0

Simplest way of Email Validation.

EditText TF;
public Button checkButton;

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}" +
          ")+"
      );
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

   TF=(EditText) findViewById(R.id.TF);
   checkButton=(Button) findViewById(R.id.checkButton);

    checkButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
           String email=TF.getText().toString();
           if(checkEmail(email))
              Toast.makeText(getApplicationContext(),"Valid Email Addresss", Toast.LENGTH_SHORT).show();
           else
              Toast.makeText(getApplicationContext(),"Invalid Email Addresss", Toast.LENGTH_SHORT).show();
    }
    });
}
private boolean checkEmail(String email) {
    return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}}
Andro Selva
  • 53,910
  • 52
  • 193
  • 240
crazyandro
  • 27
  • 4
-1

Kotlin Extension Function

fun EditText.isValidEmail() : Boolean{
    return if(Pattern
            .compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")
            .matcher(text.toString()).matches()){
        true
    }else {
        hint = context.getString(R.string.invalid_email_adress)
        false
    }
}

Use

if(!emailEt.isValidEmail()){
    return
}
Mohit Singh
  • 177
  • 2
  • 9