androidkotlinandroid-jetpackandroid-jetpack-composeandroid-jetpack-compose-text

Jetpack Compose equivalent to InputFilter?


I'm looking for an equivalent method of EditText's InputFilter in Jetpack Compose TextField.

Because I'm trying to prevent users input unwanted values like %@*()- characters for example.


Solution

  • There is a solution with Regex here:

    @Composable
    fun FilteredTextField(
        text: String,
        onChanged: (String) -> Unit,
        ignoredRegex: Regex
    ) {
        TextField(value = text,
            onValueChange = {
                if (!it.contains(ignoredRegex)) onChanged(it)
            }
        )
    }
    

    Using:

    @Composable
    fun FilteredTextFieldDemo() {
        var text by remember { mutableStateOf("") }
        FilteredTextField(
            text = text,
            onChanged = { text = it },
            ignoredRegex = Regex("[%@*()-]")
        )
    }