0

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.?
Filipe Cruz
  • 81
  • 1
  • 10

4 Answers4

4

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)) {
Sandesh Khutal
  • 1,712
  • 1
  • 4
  • 17
1

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
rost
  • 3,767
  • 2
  • 10
  • 25
0

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?

cactustictacs
  • 17,935
  • 2
  • 14
  • 25
0

As a kotlin infix

    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()
}
Supun Ayeshmantha
  • 499
  • 1
  • 5
  • 9