Home > database >  Kotlin, Android email validation
Kotlin, Android email validation

Time:05-05

I have a firebase conection in my android app where I collect email and password with the following code

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.?

CodePudding user response:

Try this Patten behalf of default pattern.It will gives you proper results.

    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)) {

CodePudding user response:

Sandesh's answer might be good enough for what you need to do, but full RFC-compliant email address validation (especially with a regex) is a famously complex problem, so just be aware there are some limits to the accuracy!

There's some discussion about it on SE here: How can I validate an email address using a regular expression?

  • Related