Show Errors
Input Errors
When prompting the user for input, the errors in the input can be shown on the screen.
Adding a text view component to the form in the view is the used approach, the text should be red.
The view model should have the string variable that is bound to the text view i.e. an error message, and also the function that should validate the input.
The function is called after clicking the form submission button, the function returns a boolean value, if the returned value is false the error message appears specifying the error, otherwise the execution of the on click command continues.
Example
fun validateInput(): Boolean {
val name = nameBinding.value
val email = emailBinding.value ?: ""
val phone = localPhoneBinding.value
if (name.isNullOrBlank()) {
errorTextBinding.value = "Please enter your name".localized()
return false
}
if (email.isBlank() || email.contains('@').not() || email.contains('.').not()) {
errorTextBinding.value = "Please enter a valid email".localized()
return false
}
if (phone.isNullOrBlank()) {
errorTextBinding.value = "Please enter a valid phone number".localized()
return false
}
errorTextBinding.value = ""
return true
}
No Comments