I am using Android Data Binding framework I have suppose an EditText for login form with username as below
You can also add validation on edit text like this.
Layout file
BindingUtils
object BindingUtils {
@BindingAdapter(value = ["error", "rule", "android:watcher"], requireAll = true)
@JvmStatic
fun watcher(textInputLayout: com.google.android.material.textfield.TextInputLayout, errorMsg: String, rule: ValidationRule, watcher: TextWatcher) {
textInputLayout.editText?.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
textInputLayout.error = null
if (rule == ValidationRule.EMPTY && !ValidationUtils.isValidEmail(p0.toString())) textInputLayout.error = errorMsg
if (rule == ValidationRule.PASSWORD && !ValidationUtils.isValidPassword(p0.toString())) textInputLayout.error = errorMsg
}
})
}
}
ValidationRule
enum class ValidationRule{
EMPTY, EMAIL, PASSWORD
}
Don't forget to set the watcher in fragment or activity like this
binding.watcher = object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
}