'Kotlin, Android email validation

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


Solution 1:[1]

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

Solution 2:[2]

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?

Solution 3:[3]

With android SDK you can use standart pattern from android.util

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

usage:

email.isValidEmail() // return true or false

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sandesh KhutalSaheb
Solution 2 cactustictacs
Solution 3 rost