Jetpack Compose equivalent to InputFilter?
H

2

6

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.

Horsewhip answered 5/6, 2021 at 3:35 Comment(0)
H
8

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("[%@*()-]")
    )
}
Horsewhip answered 5/6, 2021 at 3:35 Comment(0)
J
1

If you just want to display the numberOnly keyboard, we can do this way:

TextField(
     value = textState,
     onValueChange = { text ->
         textState = text
     },
     keyboardOptions = KeyboardOptions.Default.copy(
         keyboardType = KeyboardType.NumberPassword
     ),
     visualTransformation = VisualTransformation.None
)
Jubilee answered 25/3, 2023 at 20:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.