How to prevent the user from entering two dots in a text field jetpack compose

Viewed 79

I have a Text Field in android jetpack compose, which used to get number from user including floating points. How to prevent user from entering 2 dots in the input. For Eg: Number should be 56.54,.266, 367.5

Should not be like this: 34.3.5

1 Answers

You can use onValueChange of TextField to filter the text:

@Composable
fun MyTextField(
) {
    var text by remember { mutableStateOf("") }
    TextField(
        keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
        value = text,
        onValueChange = {
            val newString = it.filter { char ->
                char == ".".first()
            }
            if (newString.length <= 1)
                text = it
        }
    )
}

Related