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


当前回答

你可以这样写一个Kotlin扩展:

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

然后像这样调用它:

email.isValidEmail()

其他回答

可以使用正则表达式。大致如下。

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

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

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

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

这是Android Studio的建议:

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

使用扩展函数的最简单的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()

然后你可以这样验证:

"testemail6589@gmail.com".isEmailValid()

如果你在kotlin-multiplatform中没有访问Pattern,这是等价的:

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

你可以通过oval.jar文件在android中进行任何类型的验证。OVal是一种实用的、可扩展的通用验证框架,适用于任何类型的Java对象。

点击这个链接:http://oval.sourceforge.net/userguide.html

你可以从这里下载:http://oval.sourceforge.net/userguide.html#download

您可以通过在变量中设置标记来使用验证

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