dazai
dazai

Reputation: 716

How to hide error on password field after user types the right password

I have this error that comes up when the user inputs a wrong password or a password that doesn't meet the requirements. The thing is, when the user writes the right password, the error is still there even if the user can login so how can I turn it off when the password is right?

This is the part I'm talking about:

        loginViewModel.loginFormState.observe(this, Observer {
            val loginState = it ?: return@Observer

            binding.btnLogin.isEnabled = loginState.isDataValid
            if (loginState.emailError != null) {
                binding.etEmail.error = getString(loginState.emailError)
            }
            if (loginState.passwordError != null) {
                // this is the error i need to turn off
                binding.tfPassword.error = getString(loginState.passwordError)
            }
        })

        binding.etEmail.afterTextChanged {
            loginViewModel.loginDataChanged(
                binding.etEmail.text.toString(),
                binding.etPassword.text.toString()
            )
        }

        binding.etPassword.afterTextChanged {
            loginViewModel.loginDataChanged(
                binding.etEmail.text.toString(),
                binding.etPassword.text.toString()
            )
        }
    }


    private fun TextInputEditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
        this.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(editable: Editable?) {
                afterTextChanged.invoke(editable.toString())

            }

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
        })
    }
}

Upvotes: 0

Views: 70

Answers (1)

Marcin Szajna
Marcin Szajna

Reputation: 51

To get rid of error in TextInputEditText you need to pass null to error parameter. I see you do not handle a state in which you pass a correct password. In your case

if (loginState.passwordError != null) {
    binding.tfPassword.error = getString(loginState.passwordError)
} else { // you are missing this else statement
    binding.tfPassword.error = null
}

or even prettier

binding.tfPassword.error = loginState.passwordError?.getString(loginState.passwordError)

which will assign null to tfPassword.error when passwordError will be null. Of course this will also apply to etEmail.error

Upvotes: 1

Related Questions