Android 我应该如何验证电子邮件地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1819142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:40:25  来源:igfitidea点击:

How should I validate an e-mail address?

androidemail-validation

提问by znq

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.EmailValidatordoesn'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?

在 Android 中验证电子邮件地址(例如来自用户输入字段)的好技术是什么?org.apache.commons.validator.routines.EmailValidator似乎不可用。是否有任何其他库已经包含在 Android 中,或者我是否必须使用 RegExp?

采纳答案by Glen

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)

显然,以下是一个正则表达式,它正确验证了大多数符合RFC 2822的电子邮件地址,(并且仍然会在诸如“[email protected]”之类的事情上失败,org.apache.commons.validator 也是如此。例程.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.

如果您有一些特定于业务逻辑的验证,那么您可以使用正则表达式执行该验证,例如必须是 gmail.com 帐户或其他内容。

回答by mindriot

Another option is the built in Patternsstarting with API Level 8:

另一种选择是从 API 级别 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:

来自@AdamvandenHoven 的一行解决方案:

public final static boolean isValidEmail(CharSequence target) {
  return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}

回答by Andrei Buneyeu

Next pattern is used in K-9 mail:

在 K-9 邮件中使用下一个模式:

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

回答by Luten

Since API 8 (android 2.2) there is a pattern: android.util.Patterns.EMAIL_ADDRESS http://developer.android.com/reference/android/util/Patterns.html

由于 API 8 (android 2.2) 有一个模式: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

如果电子邮件有效则返回 true

UPD: This pattern source code is:

UPD:此模式源代码是:

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

参考: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.

所以你可以自己构建它以兼容 API < 8。

回答by Salman Nazir

We have simple Email pattern matcher now

我们现在有简单的电子邮件模式匹配器

 private static boolean isValidEmail(String email) {
        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

回答by Pankaj Talaviya

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

回答by Matteo

This is Android Studio suggestions:

这是 Android Studio 的建议:

public static boolean isEmailValid(String email) {
    return !(email == null || TextUtils.isEmpty(email)) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

回答by Danilo Lemes

You could write a Kotlin extension like this:

您可以像这样编写 Kotlin 扩展:

fun String.isValidEmail() =
        this.isNotEmpty() && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()

And then call it like this:

然后像这样调用它:

email.isValidEmail()

回答by Victor Odiah

use android:inputType="textEmailAddress" as below:

使用 android:inputType="textEmailAddress" 如下:

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

回答by Mudassir

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.

注意:检查上面给出的正则表达式,不要按原样使用它。