Allow ONLY Letters in Keyboard - Jetpack Compose

Viewed 750

I'm trying to create a TextField in Jetpack Compose for users to enter their first and last name.

Is there a way to allow ONLY letters and whitespaces ([a-zA-Z\s]) as input? I've tried every single option available, including KeyboardType.Text, KeyboardType.Ascii, KeyboardType.Uri, but they all show numbers!

Am I missing something obvious? Honestly, I'm kind of shocked that Google doesn't offer this option out of the box.

2 Answers

Try this:

val pattern = remember { Regex("[a-zA-z\\s]*") }
var text by remember { mutableStateOf("") }

TextField(
    value = text,
    onValueChange = {
        if (it.matches(pattern)) {
            text = it
        }
    }
)

In Android it's not possible to show a keyboard containing only letters (and it's not related to compose). Keyboard apps don't support it either.

There are other kinds of keyboards (like number-only keyboard), but the view of the keyboard is still controlled by the keyboard app.

It's best to filter the given input based on the needed criteria. For example:

onValueChange = {
    text = it.letters()
}

private fun String.letters() = filter { it.isLetter() }
Related