Kotlin, Android电子邮件验证



我有一个firebase连接在我的android应用程序,我收集电子邮件和密码与以下代码

private fun validateData() {
email = binding.emailText.text.toString().trim()
password = binding.passwordText.text.toString().trim()
passwordrepeat = binding.passwordText2.text.toString().trim()
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
binding.emailTF.error = "Invalid email format"
} else if (TextUtils.isEmpty(password)) {
binding.passwordTF.error = "Please enter password"
}else if(TextUtils.isEmpty(passwordrepeat)){
binding.passwordTF2.error="Please repeat password"
}else if(password != passwordrepeat) {
binding.passwordTF2.error="Passwords don´t match"
}else if (password.length < 6){
binding.passwordTF.error = "Password must have atleast 6 caracters"
}else{
firebaseSignUp()
}
}```
How can I make a new if to validate emails that end only in @test.pt for example.?

尝试此模式代表默认模式。它会给你正确的结果。

val 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}" +
")+"
)
fun isValidString(str: String): Boolean{
return EMAIL_ADDRESS_PATTERN.matcher(str).matches()
}
//Replace with your email validation condition.
if (!isValidString(email)) {

对于android SDK,您可以使用android.util中的标准模式

fun CharSequence?.isValidEmail() = !isNullOrEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()

用法:

email.isValidEmail() // return true or false

Sandesh的答案可能足够好,但完全符合rfc的电子邮件地址验证(特别是使用正则表达式)是一个出了名的复杂问题,所以要注意准确性有一些限制!

在SE上有一些关于它的讨论:我如何使用正则表达式验证电子邮件地址?

作为kotlin中缀

fun String.isValidEmail(): Boolean {
val 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}" +
")+"
)
return EMAIL_ADDRESS_PATTERN.matcher(this).matches()
}

最新更新