【问题标题】:How can i validate multiple editText fields and enable button?如何验证多个 editText 字段并启用按钮?
【发布时间】:2019-10-12 10:15:40
【问题描述】:

我正在尝试弄清楚如何验证 6 个 EditText 输入字段并启用按钮 button_step_one_next_FSF.isEnabled = true 当一切都符合我的条件时。 我想在不创建 TextWatcher 对象的情况下使用这个 util 类验证所有内容。

这是我的editText util类

inline fun EditText.onTextChange(crossinline f: (s: CharSequence?) -> Unit) {
val listener = object : TextWatcher {
    override fun onTextChanged(s: CharSequence, start: Int,
                               before: Int, count: Int) {
        f(s)
    }

    override fun afterTextChanged(s: Editable?) {}
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
}
addTextChangedListener(listener)

}

这里是简短的验证方法示例

 private fun validateInput() {

    edit_text_name.onTextChange { s ->
        val name: String = s?.toString() ?: ""
        if (!name.isNameNotValid()) {
            text_input_name.isEndIconVisible = true
            text_input_name.isErrorEnabled = false
        } else {
            text_input_name.error = getString(R.string.error_not_valid_name)
            text_input_name.isEndIconVisible = false
        }
    }
    edit_text_surname.onTextChange { s ->
        val surname: String = s?.toString() ?: ""
        if (!surname.isNameNotValid()) {

            text_input_surname.isEndIconVisible = true
            text_input_surname.isErrorEnabled = false

        } else {
            text_input_surname.error = getString(R.string.error_not_valid_surname)
            text_input_surname.isEndIconVisible = false
        }
    }

【问题讨论】:

    标签: android validation kotlin android-edittext textwatcher


    【解决方案1】:

    我刚刚在 TextWatcher lambda 表达式的每个验证结束时添加了这个方法 checkButtonEnableState(),它解决了我的问题!

    private fun checkButtonEnableState() {
        button_step_one_next_FSF.isEnabled =
            (!edit_text_name.text.toString().isNameNotValid()
                    && !edit_text_surname.text.toString().isNameNotValid()
                    && edit_text_password_FSF.text.toString().isValidPassword()
                    && edit_text_password_confirm_FSF.text.toString().isValidPassword()) &&
                    (edit_text_password_confirm_FSF.text.toString() == edit_text_password_FSF.text.toString())
    } 
    

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多