3

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.

kc_dev
  • 578
  • 1
  • 6
  • 21

2 Answers2

3

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
        }
    }
)
Ehsan msz
  • 1,774
  • 2
  • 13
  • 26
  • 1
    This is certainly a step in the right direction, but ideally, I would like to prevent showing non-letters in the first place. I guess that's not possible as of now... – kc_dev Jan 03 '22 at 16:20
2

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() }
Adib Faramarzi
  • 3,798
  • 3
  • 29
  • 44