如何在 jetpack compose 中显示多个 TextField 的错误消息

How to display error messages for multiple TextField in jetpack compose

如何在 jetpack compose 中显示多个 TextField 的错误消息。 只有一个字段:

private var isError by mutableStateOf(false)

private fun validate(text: String){
    isError = if(text.isEmpty()){
        true
    }else{
        android.util.Patterns.EMAIL_ADDRESS.matcher(text).matches()
    }

    Log.i("Boolean",isError.toString())

}

    TextField(value = email,placeholder = { Text(text = "E-mail")},
            onValueChange = {
                email=it
                isError = false
            },
            shape = RoundedCornerShape(8.dp),
            colors = TextFieldDefaults.textFieldColors(
                    focusedIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent,
                    disabledIndicatorColor = Color.Transparent

            ),
            singleLine = true,
            isError = isError,
            keyboardActions = KeyboardActions { validate(email) },
            modifier=Modifier.align(Alignment.CenterHorizontally),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
            leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = null) })

我有一个包含多个 TextField 的表单,如何逐一验证。例如,如果我有两个字段,名称和电子邮件。我考虑过对所有字段进行循环,但我不知道这是否是最佳做法。谁能帮帮我

    var nome by rememberSaveable{ mutableStateOf("")}
    var email by rememberSaveable{ mutableStateOf("") }

       

 TextField(value = nome,placeholder = { Text(text = "Nome")},
                onValueChange = {
                    nome=it
                },
                shape = RoundedCornerShape(8.dp),
                colors = TextFieldDefaults.textFieldColors(
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent,
                        disabledIndicatorColor = Color.Transparent

                ),
                modifier=Modifier.align(Alignment.CenterHorizontally),
                leadingIcon = { Icon(imageVector = Icons.Default.Person, contentDescription = null) })

        Spacer(modifier = Modifier.padding(5.dp))


        TextField(value = email,placeholder = { Text(text = "E-mail")},
                onValueChange = {
                    email=it
                   
                },
                shape = RoundedCornerShape(8.dp),
                colors = TextFieldDefaults.textFieldColors(
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent,
                        disabledIndicatorColor = Color.Transparent

                ),
                modifier=Modifier.align(Alignment.CenterHorizontally),
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
                leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = null) })

    Spacer(modifier = Modifier.padding(5.dp))


    Button(
            onClick = { verifyEmpty(strings=validate) },
            colors = ButtonDefaults.buttonColors(
                    contentColor = colorResource(id = R.color.marron),
                    backgroundColor = colorResource (id = R.color.pastel_green)
            ),
    ) {
        Text(text = stringResource(id = R.string.view_cad),
                color= colorResource(id = R.color.marron))
    }

当您在两个以上的视图之间找到如此多的共同点时,是时候将其移至单独的可组合项中了。您可以指定参数中的所有差异,而不是为每个视图重复相同的设置。

我建议您为自定义文本字段创建状态 class。我将存储文本、错误文本和验证器逻辑。因此,您可以在需要时调用验证:单击按钮或键盘完成按钮:

@Composable
fun TestView(
) {
    val nomeState = rememberErrorTextFieldState("", validate = { text ->
        when {
            text.isEmpty() -> {
                "text.isEmpty()"
            }
            else -> null
        }
    })
    val emailState = rememberErrorTextFieldState("", validate = { text ->
        when {
            text.isEmpty() -> {
                "text.isEmpty()"
            }
            !android.util.Patterns.EMAIL_ADDRESS.matcher(text).matches() -> {
                "pattern doesn't match"
            }
            else -> null
        }
    })

    Column {
        ErrorTextField(
            state = nomeState,
            placeholderText = "nome",
            leadingIconVector = Icons.Default.Person,
            modifier = Modifier.align(Alignment.CenterHorizontally),
        )
        ErrorTextField(
            state = emailState,
            placeholderText = "email",
            leadingIconVector = Icons.Default.Email,
            modifier = Modifier.align(Alignment.CenterHorizontally),
        )
        Button(
            onClick = {
                listOf(nomeState, emailState).forEach(ErrorTextFieldState::validate)
            },
        ) {
            Text(text = "stringResource(id = R.string.view_cad)")
        }
    }
}


@Composable
fun ErrorTextField(
    state: ErrorTextFieldState,
    placeholderText: String,
    leadingIconVector: ImageVector,
    modifier: Modifier,
) {
    Column {
        val error = state.error
        TextField(
            value = state.text,
            onValueChange = { state.updateText(it) },
            placeholder = { Text(text = placeholderText) },
            shape = RoundedCornerShape(8.dp),
            colors = TextFieldDefaults.textFieldColors(
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                disabledIndicatorColor = Color.Transparent,
                errorCursorColor = Color.Red
            ),
            singleLine = true,
            isError = error != null,
            leadingIcon = { Icon(imageVector = leadingIconVector, contentDescription = null) },
            keyboardActions = KeyboardActions {
                state.validate()
            },
            modifier = modifier,
        )
        if (error != null) {
            Text(
                error,
                color = Color.Red,
            )
        }
    }
}

@Composable
fun rememberErrorTextFieldState(
    initialText: String,
    validate: (String) -> String? = { null },
): ErrorTextFieldState {
    return rememberSaveable(saver = ErrorTextFieldState.Saver(validate)) {
        ErrorTextFieldState(initialText, validate)
    }
}

class ErrorTextFieldState(
    initialText: String,
    private val validator: (String) -> String?,
) {
    var text by mutableStateOf(initialText)
        private set

    var error by mutableStateOf<String?>(null)
        private set

    fun updateText(newValue: String) {
        text = newValue
        error = null
    }

    fun validate() {
        error = validator(text)
    }

    companion object {
        fun Saver(
            validate: (String) -> String?,
        ) = androidx.compose.runtime.saveable.Saver<ErrorTextFieldState, String>(
            save = { it.text },
            restore = { ErrorTextFieldState(it, validate) }
        )
    }
}