您可以驗證使用者在文字欄位中輸入的內容,例如輸入姓名、電子郵件地址、地址或其他聯絡資訊。這項驗證可減少錯誤,並節省使用者時間。
版本相容性
這個實作方式需要將專案 minSDK 設為 API 級別 21 以上。
依附元件
在使用者輸入時驗證輸入內容
使用下列程式碼顯示欄位輸入內容,並在使用者輸入內容時驗證文字。如果系統未驗證資訊,則會顯示錯誤訊息,協助使用者修正輸入內容。
class EmailViewModel : ViewModel() { var email by mutableStateOf("") private set val emailHasErrors by derivedStateOf { if (email.isNotEmpty()) { // Email is considered erroneous until it completely matches EMAIL_ADDRESS. !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() } else { false } } fun updateEmail(input: String) { email = input } } @Composable fun ValidatingInputTextField( email: String, updateState: (String) -> Unit, validatorHasErrors: Boolean ) { OutlinedTextField( modifier = Modifier .fillMaxWidth() .padding(10.dp), value = email, onValueChange = updateState, label = { Text("Email") }, isError = validatorHasErrors, supportingText = { if (validatorHasErrors) { Text("Incorrect email format.") } } ) } @Preview @Composable fun ValidateInput() { val emailViewModel: EmailViewModel = viewModel<EmailViewModel>() ValidatingInputTextField( email = emailViewModel.email, updateState = { input -> emailViewModel.updateEmail(input) }, validatorHasErrors = emailViewModel.emailHasErrors ) }
程式碼的重點
- 定義可重複使用
OutlinedTextField
元件的可組合函式,並新增必要參數,以便在使用者輸入時顯示驗證器錯誤訊息。 EmailViewModel
可用於維持狀態,並提供電子郵件驗證邏輯。- 如果
isError
為 true,UI 會提供驗證錯誤狀態的視覺指標。 - 在輸入完整且正確的電子郵件地址之前,元件會顯示「電子郵件格式不正確」。
結果


包含此指南的集合
本指南是精選的快速指南系列之一,涵蓋更廣泛的 Android 開發目標:

顯示文字
文字是所有使用者介面的核心,瞭解在應用程式中顯示文字的不同方式,以提供優質的使用者體驗。

要求使用者輸入內容
瞭解如何讓使用者透過輸入文字和其他輸入方式與應用程式互動。
有問題或意見回饋嗎?
歡迎前往常見問題頁面,瞭解快速指南或與我們聯絡,分享您的想法。