Vygintas B
Vygintas B

Reputation: 1694

Disable emoji input on TextField

Can I disable emoji soft keyboard input for TextField?

Currently using KeyboardOptions(keyboardType = KeyboardType.Ascii) as keyboard options, but it doesn't work. I'm still able to enter emoji.

Documantation says this doesn't guarantee it will work with all keyboards.

My question:

Is there any other way to disable emoji, or I have to filter input manually?

Upvotes: 1

Views: 2401

Answers (2)

Pratiksha Borkar
Pratiksha Borkar

Reputation: 11

You can disable emoji's in TextField, outlinedField in jetpack compose by using keyboard type

keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password) keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Email)

Upvotes: 1

beyondtheteal
beyondtheteal

Reputation: 858

Unfortunately, there doesn't seem to be a good way to filter input from the keyboard like there was in traditional Android. Any use of regex to remove values will place your cursor in the wrong spot, especially if someone is editing the string from the middle.

Instead, what I've seen suggested (one sample answer here), is to show an error when the user inputs invalid content.

I used a regex filter from this answer to show an error when emoji is present.

    fun containsEmoji(emailStr: String?) =
        Pattern
            .compile("\\p{So}+", Pattern.CASE_INSENSITIVE)
            .matcher(emailStr.toString()).find()

    var emailText by remember { mutableStateOf(TextFieldValue("")) }
    var containsEmoji by remember { mutableStateOf(false) }

    Column {
        TextField(
            modifier = Modifier.fillMaxWidth(),
            value = emailText,
            onValueChange = {
                emailText = it
                containsEmoji = containsEmoji(it.text)
            },
            label = { Text(text = "Your message here") }
        )
        if (containsEmoji) {
            Text("Please remove emoji!")
        }
    }

enter image description here

Upvotes: 5

Related Questions