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 companyName = companyNameBinding.value
val country = country?.name ?: ""
val email = emailBinding.value ?: ""
val callingCode = callingCodeBinding.value
val phone = localPhoneBinding.value
if (companyName!!.isBlank()) {
errorTextBinding.value = "Please enter a company name".localized()
return false
}
if (country!!.isBlank()) {
errorTextBinding.value = "Please select a country".localized()
return false
}
if (email.isBlank() || email.contains('@').not() || email.contains('.').not()) {
errorTextBinding.value = "Please enter a valid email".localized()
return false
}
if (callingCode!!.isBlank()) {
errorTextBinding.value = "Please select a country calling code".localized()
return false
}
if (phone!!.isBlank()) {
errorTextBinding.value = "Please enter a valid phone number".localized()
return false
}
errorTextBinding.value = ""
return true
}