在Android中验证电子邮件地址(例如从用户输入字段)的好技术是什么?emailvalidator似乎不可用。还有其他库做这个,包括在Android已经或我必须使用RegExp?


当前回答

Linkify类有一些非常有用的helper方法,包括用于获取电话号码和电子邮件地址的正则表达式,例如:

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

其他回答

Following是我用的。然而,它包含额外的字符比正常的电子邮件,但这是对我的要求。

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

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

解释,

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

对于正则表达式爱好者来说,我迄今为止发现的最好的(例如与RFC 822一致)电子邮件模式如下(在PHP提供过滤器之前)。我想对于那些使用API < 8的人来说,将其翻译成Java很容易:

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

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

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

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

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

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