在Android中验证电子邮件地址(例如从用户输入字段)的好技术是什么?emailvalidator似乎不可用。还有其他库做这个,包括在Android已经或我必须使用RegExp?
当前回答
这是kotlin使用扩展函数的最佳方式
fun String.isEmailValid(): Boolean {
return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}
其他回答
对于正则表达式爱好者来说,我迄今为止发现的最好的(例如与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 ;
}
如果您正在使用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文件复制到您的项目中并引用它。您可以从这个链接获得Patterns.java的源代码
电子邮件验证在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
}
这是kotlin使用扩展函数的最佳方式
fun String.isEmailValid(): Boolean {
return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}
Linkify类有一些非常有用的helper方法,包括用于获取电话号码和电子邮件地址的正则表达式,例如:
http://developer.android.com/reference/android/text/util/Linkify.html
推荐文章
- 从资产中读取文件
- 在不活动的地方调用getLayoutInflater()
- 设置Android布局元素的背景颜色
- 错误:'keytool'不能被识别为内部或外部命令、可操作程序或批处理文件
- 在应用程序本身中更改Locale
- apk (.apk)和应用程序包(.aab)的区别
- 如何设置超时在改造库?
- Android - SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度
- TextView的字体大小在Android应用程序改变字体大小从本机设置
- 如何模拟Android杀死我的进程
- 禁用EditText闪烁光标
- Android Eclipse -无法找到*.apk
- 设置TextView文本从html格式的字符串资源在XML
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Android加载JS包失败