How should I validate an e-mail address?

后端 未结 30 2218
臣服心动
臣服心动 2020-11-22 08:25

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

30条回答
  •  我在风中等你
    2020-11-22 09:16

    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:

    "testemail6589@gmail.com".isEmailValid()
    

    If you are in kotlin-multiplatform without access to Pattern, this is the equivalent:

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

提交回复
热议问题