Function

maxLengthTrim

Limits the total length of the text field to maxLength characters by truncating inserted characters.

BasicTextFieldInputTransformationMaxLengthCustom

@Sampled
@Composable
fun BasicTextFieldInputTransformationMaxLengthCustom() {
    val state = remember { TextFieldState() }
    BasicTextField(
        state,
        inputTransformation =
            object : InputTransformation {
                override fun SemanticsPropertyReceiver.applySemantics() {
                    // The output transformation formats "1234567890" to "(123) 456-7890",
                    // which is 14 characters long. We set the accessibility maximum length
                    // to 14 so screen readers announce the correct limit.
                    maxTextLength = 14
                }

                override fun TextFieldBuffer.transformInput() {
                    if (length > 10) {
                        delete(10, length)
                    }
                }
            },
        outputTransformation =
            OutputTransformation {
                if (length > 0) insert(0, "(")
                if (length > 4) insert(4, ") ")
                if (length > 9) insert(9, "-")
            },
    )
}

Content updated: