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

发布于 2024-08-12 20:43:38 字数 283 浏览 5 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

忆沫 2024-08-19 20:43:39

使用扩展函数的最简单的 Kotlin 解决方案:

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

然后您可以像这样进行验证:

"[email protected]".isEmailValid()

如果您在 kotlin-multiplatform 中无法访问 Pattern,则这是等效的:

fun String.isValidEmail() = Regex(emailRegexStr).matches(this)

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)
遮了一弯 2024-08-19 20:43:39

这是 kotlin 使用扩展函数的最佳方法

fun String.isEmailValid(): Boolean {
        return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
    }

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()
    }
握住你手 2024-08-19 20:43:39

在您想要验证电子邮件 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;
   }
}

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;
   }
}
最单纯的乌龟 2024-08-19 20:43:39

对于电子邮件验证,android 提供了一些 内置模式。但它只支持 < strong>API 级别 8 及以上。

以下是使用该模式检查电子邮件验证的代码。

  private boolean Email_Validate(String email) 
  {
    return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
  }

确保执行此方法后,您应该检查如果此方法返回true,则您允许保存电子邮件,如果此方法返回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.

那请放手 2024-08-19 20:43:39

我强烈建议您不要尝试“验证”电子邮件地址,否则您只会无缘无故地投入大量工作。

只需确保输入的内容不会破坏您自己的代码 - 例如,没有可能导致异常的空格或非法字符。

其他任何事情只会让你付出大量的努力而回报却微乎其微......

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

陌路终见情 2024-08-19 20:43:39
    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;
}
    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;
}
一萌ing 2024-08-19 20:43:39

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
  }

此方法用于检查有效的电子邮件 ID 格式。

    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
    }

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}
quot;
        val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE)
        val matcher = pattern.matcher(email)
        if (!matcher.matches()) {
            isValid = false
        }
        return isValid
    }
心碎的声音 2024-08-19 20:43:39

如果您使用的是 API 8 或更高版本,则可以使用现成的 Patterns 类来验证电子邮件。示例代码:

public final static boolean isValidEmail(CharSequence target) {
    if (target == null) 
        return false;

    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}

如果您支持的 API 级别低于 8,那么您只需将 Patterns.java 文件复制到您的项目中并引用它即可。您可以从 此链接

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

冰葑 2024-08-19 20:43:39

这是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 将匹配它,如果

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, -)

示例一些特殊的匹配电子邮件

[email protected]
[email protected]
[email protected]

您可以根据您的情况修改此模式,然后验证经过

fun isValidEmail(email: String): Boolean {
    return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}

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()
}
迷鸟归林 2024-08-19 20:43:39

尝试这个简单的方法,它不能接受以数字开头的电子邮件地址:

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 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;
}
风铃鹿 2024-08-19 20:43:39

试试这个代码..它真的有效..

            if (!email
                    .matches("^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"))
            {
                Toast.makeText(getApplicationContext(), "Email is invalid",
                        Toast.LENGTH_LONG).show();
                return;
            }

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;
            }
趁年轻赶紧闹 2024-08-19 20:43:39

以下是我用过的。然而,它比普通电子邮件包含额外的字符,但这对我来说是一个要求。

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

这个问题的答案:-
验证电子邮件的要求带有给定点的邮件地址

解释

  1. - (?!.*?..) “Negative Lookhead” 否定 2 个连续的点。
  2. [A-Za-z0-9.!#\$\%\&\'*+-/\=\?\^_`{\|}\~]+ 至少一个
    定义的字符。 (“\”用于转义)。
  3. @ 可能有一个“@”。
  4. [A-Za-z0-9]+ 然后至少定义一个字符。
  5. [A-Za-z0-9-.]* 定义的字符的零次或任意重复。
  6. [A-Za-z0-9]+ 点后至少一个字符。

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.
儭儭莪哋寶赑 2024-08-19 20:43:39

这里的关键是您要完全验证电子邮件地址。您不仅想检查语法的正确性,还想检查电子邮件地址是否真实。

两个明显的原因:真实用户经常会错误地输入他们的电子邮件地址,一些用户可能会输入虚假的电子邮件地址。因此,您需要进行语法检查和存在性检查。

我在 Android 上找到的最好方法是使用免费的 Cloudmersive Validation API为了这。

代码如下所示:

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

我在所有应用程序中都使用了它,这很棒,因为我可以在输入时验证 UX 中的电子邮件地址。

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.

挥剑断情 2024-08-19 20:43:39

根据 Patterns.EMAIL_ADDRESS,此电子邮件是正确的“[email protected]” 。因此,我修改了 Patterns.EMAIL_ADDRESS 中的正则表达式并增加了域的最小长度。
这是 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()

我刚刚将域部分从 {0,25} 更改为 {1,25}。

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

我的奇迹 2024-08-19 20:43:39

请注意,大多数正则表达式对于国际域名 (IDN) 和新顶级域(如 .mobi 或 .info)无效(如果您检查国家/地区代码或 .org、.com、.gov 等)。

有效的检查应将本地部分(at 符号之前)和域部分分开。您还应该考虑本地部分和域的最大长度(总共 255 个字符,包括 at 符号)。

最好的方法是以 IDN 兼容格式转换地址(如果需要)、验证本地部分 (RFC)、检查地址长度并检查域的可用性(DNS MX 查找)或简单地发送电子邮件。

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.

有木有妳兜一样 2024-08-19 20:43:39

Linkify 类有一些非常有用的可能相关的帮助器方法,包括旨在获取电话号码和电子邮件地址的正则表达式等:

http://developer.android.com/reference/android/text/util/Linkify.html

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

陌上青苔 2024-08-19 20:43:39

我使用了以下代码。这非常有效。我希望这会对您有所帮助。

if (validMail(yourEmailString)){
   //do your stuf
 }else{
 //email is not valid.
}

并使用以下方法。如果电子邮件有效,则返回 true。

    private boolean validMail(String yourEmailString) {
    Pattern emailPattern = Pattern.compile(".+@.+\\.[a-z]+");
    Matcher emailMatcher = emailPattern.matcher(emailstring);
    return emailMatcher.matches();
}

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();
}
难如初 2024-08-19 20:43:39

电子邮件是您的电子邮件。

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

    }

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

    }
情绪操控生活 2024-08-19 20:43:39

对于正则表达式爱好者来说,我从现在起发现的最好的(例如与 RFC 822 一致)电子邮件模式如下(在 PHP 提供的过滤器之前)。我想对于那些使用 API 的人来说,将其翻译成 Java 是很容易的。 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 ;
}

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 ;
}
谎言月老 2024-08-19 20:43:38

另一个选项是从 API 级别 8 开始的内置 Patterns

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

模式可查看源

OR :

来自 @AdamvandenHoven 的一行解决方案

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

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();
}
梦回梦里 2024-08-19 20:43:38

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

您可以使用函数

private boolean checkEmail(String email) {
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}

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();
}
记忆里有你的影子 2024-08-19 20:43:38

从 API 8 (android 2.2) 开始,有一个模式:android.util.Patterns.EMAIL_ADDRESS
http://developer.android.com/reference/android/util/Patterns.html

因此,您可以使用它来验证 yourEmailString:

private boolean isValidEmail(String email) {
    Pattern pattern = Patterns.EMAIL_ADDRESS;
    return pattern.matcher(email).matches();
}

如果电子邮件有效

UPD,则返回 true:
该模式源码为:

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

参考:http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/util/Patterns。 java

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

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.

饮惑 2024-08-19 20:43:38

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

Java:

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

Kotlin 函数:

 private fun isValidEmail(email: String): Boolean {
        return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches()
    }

Kotlin 扩展:

fun String.isValidEmail() =
    !TextUtils.isEmpty(this) && Patterns.EMAIL_ADDRESS.matcher(this).matches()

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()
橙幽之幻 2024-08-19 20:43:38

不要使用正则表达式。

显然,以下是一个正则表达式,它可以正确验证大多数符合 RFC 2822,(并且在诸如“[email]之类的事情上仍然会失败protected]”,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])+)\])

可能是验证电子邮件的最简单方法,只需将确认电子邮件发送到所提供的地址,然后它会被退回无效。

如果您想执行一些基本检查,您只需检查它的格式是否为 *@*

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

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.

一刻暧昧 2024-08-19 20:43:38

使用简单的一行代码进行电子邮件验证,

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

例如...

if (!isValidEmail(yourEdittext.getText().toString()) {
    Toast.makeText(context, "your email is not valid", 2000).show();
}

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();
}
千と千尋 2024-08-19 20:43:38

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

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

然后这样调用它:

email.isValidEmail()

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()
眼波传意 2024-08-19 20:43:38

这是 Android Studio 的建议:

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

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();
}
孤凫 2024-08-19 20:43:38

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

       <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="email"
        android:inputType="textEmailAddress"
        android:id="@+id/email"
        />

和:

       boolean isEmailValid(CharSequence email) {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(email)
                .matches();
      }

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();
      }
嗳卜坏 2024-08-19 20:43:38

您可以使用正则表达式来执行此操作。像下面这样的东西。

Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
String email = "[email protected]";
Matcher matcher = pattern.matcher(email);
boolean matchFound = matcher.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.

白日梦 2024-08-19 20:43:38

android.util 包中有一个 Patterns 类,它在这里很有用。以下是我经常用于验证电子邮件和许多其他内容的方法

private boolean isEmailValid(String email) {
    return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文