Is it possible to lock user input to Captial Letters only? capitalisation parameter in Keyboard Opti...
k
Is it possible to lock user input to Captial Letters only? capitalisation parameter in Keyboard Options launches keyboard with capital letters but also allows the user to toggle it back to lowercase. Should I use visualization transformation here?
c
Calling
.toUpperCase()
on the text when updating the state emitted should do it. The TextField itself doesn’t need to have explicit options for things like this, since you are entirely in control of how it displays and what happens when input is entered
Copy code
val textState = remember { mutableStateOf(TextFieldValue()) }
TextField(
    value = textState.value,
    onValueChange = { textState.value = it.copy(text = it.text.toUpperCase()) },
)
👍 1
k
Yeah I was just concerned that it might look inconsistent, you're operating a keyboard with lowercase letters and they're getting printed as uppercase.
s
Do not use imho visual transformation since it needs a mapping between the lowercase version and uppercase version, and the capitalization rules for some characters might create trouble for you there.
d
Are you suggesting to outright reject non capital letters?
s
No, what Casey wrote sounds good.
It was about VisualTransformation api
d
Ah, fair enough.
c
Outright rejecting non-capital letters would be easy enough using the same technique. Check if the text in
onValueChange
contains non-capital characters, and only assign
textState.value
if it passes validation
Copy code
val textState = remember { mutableStateOf(TextFieldValue()) }
TextField(
    value = textState.value,
    onValueChange = {
        if(it.text.matches("[A-Z]*".toRegex())) {
            textState.value = it 
        }
    },
)
d
Using
isErroroValue
might have better UX.
👆 1