How to show error message in OutlinedTextField in Jetpack Compose
I need to show error message in OutlinedTextField and I don't find any documentation about how to do it. I found several ways in tutorials, for example to create custom input field with hint or create Text just below input field, but they very old and maybe there is a better way. I need show error message like this:
Code:
@Composable
fun EmailInputField(value: MutableState<String>, state: AuthState) {
OutlinedTextField(
value = value.value,
onValueChange = { value.value = it },
modifier = Modifier.fillMaxWidth(1f).height(60.dp),
textStyle = TextStyle(color = Color.White),
label = { Text(text = "Email", color = Color.White) },
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = blue,
unfocusedBorderColor = Color.White
),
isError = state is AuthState.ValidationError,
singleLine = true
)
}
Solution 1:
Compose 1.0.x
doesn't support an errorMessage
field.
You can use something like:
var text by rememberSaveable { mutableStateOf("") }
var isError by rememberSaveable { mutableStateOf(false) }
fun validate(text: String) {
isError = /* .... */
}
Column {
TextField(
value = text,
onValueChange = {
text = it
isError = false
},
trailingIcon = {
if (isError)
Icon(Icons.Filled.Error,"error", tint = MaterialTheme.colors.error)
},
singleLine = true,
isError = isError,
keyboardActions = KeyboardActions { validate(text) },
)
if (isError) {
Text(
text = "Error message",
color = MaterialTheme.colors.error,
style = MaterialTheme.typography.caption,
modifier = Modifier.padding(start = 16.dp)
)
}
}