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
)
}
With M3 you can use the the supportingText
attribute that is the optional supporting text to be displayed below the text field.
val errorMessage = "Text input too long"
var text by rememberSaveable { mutableStateOf("") }
var isError by rememberSaveable { mutableStateOf(false) }
val charLimit = 10
fun validate(text: String) {
isError = text.length > charLimit
}
TextField(
value = text,
onValueChange = {
text = it
validate(text)
},
singleLine = true,
isError = isError,
supportingText = {
if (isError) {
Text(
modifier = Modifier.fillMaxWidth(),
text = "Limit: ${text.length}/$charLimit",
color = MaterialTheme.colorScheme.error
)
}
},
trailingIcon = {
if (isError)
Icon(Icons.Filled.Error,"error", tint = MaterialTheme.colorScheme.error)
},
keyboardActions = KeyboardActions { validate(text) },
)
The M2 TextField
components doesn't support an errorMessage
field.
You can easily achieve it using 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)
)
}
}