Sunday, April 25, 2021

jetpack compose - TextField error

Compose TextField Error
TextField is an equivalent widget of the android view system’s EditText widget. Jetpack compose TextField is used to enter and modify text. So, TextField is called a Text input widget of the jetpack compose library.

The following jetpack compose tutorial will demonstrate to us how we can handle errors on TextField. For example, how we can catch TextField error while users enter text on it, how we can show an error message on the TextField while an error occurred and how we can show different colors on the TextField widget to indicate that TextField generates an error.

The first question is, how we can catch an error from TextField while the user enters Text on it? The answer is TextField constructor’s ‘onValueChange’ argument allows us to catch errors in real-time while users enter text on It. We also can catch errors on TextField’s focused change.

We can make a TextField mandatory to input some text in it, if the user leaves the TextField blank then we can show an error message on the TextField immediately. Another example is if we ask for users to submit their age on a TextField and users enter text instead numbers on it then we can display an error message to the user.

We can display the error message inside the TextField itself such as on the label or the placeholder object. An android developer also can display TextField error messages outside of the TextField such as on a Text widget.

Let us explain the following tutorial code, at the top of the code, we initialize a variable to remember TextField’s error state. When TextField caused an error we set the value to true and when TextField has no error then we set its value to false. In this way, we can remember the specified TextField’s error state.

TextField constructor’s ‘isError’ argument allows us to mark whether a TextField is in an error state or not. If it is in an error state then the TextField shows different colors on it to notify users such as red color border. And its valid state TextField displays regular colors on it. Jetpack compose developers can customize the TextField error states color using its constructor’s ‘colors’ argument. Android developers can show an error message when TextField is in an error state.

This jetpack compose tutorial is written in an android studio IDE. Copy the code and run it on an emulator device or a real device to test how we handle errors for a specified TextField. We also displayed screenshots of this tutorial’s emulator output screen.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            var textState by remember { mutableStateOf(TextFieldValue()) }
            var errorState by remember { mutableStateOf(false)}
            var errorMessage by remember { mutableStateOf("")}

            var textState2 by remember { mutableStateOf(TextFieldValue()) }
            var errorState2 by remember { mutableStateOf(false)}
            var errorMessage2 by remember { mutableStateOf("")}

            TextField(
                value = textState,
                onValueChange = {
                    textState = it
                    when {
                        textState.text.isEmpty() -> {
                            errorState = true
                            errorMessage = "Name should not blank"
                        }
                        textState.text.startsWith("0") -> {
                            errorState = true
                            errorMessage = "Name should not start with zero"
                        }
                        else -> {
                            errorState = false
                            errorMessage = ""
                        }
                    }
                },
                label = {
                    Text(
                        text = if (errorState) errorMessage
                        else "Put your name here"
                    )
                },
                modifier = Modifier.fillMaxWidth(),
                isError = errorState
            )

            OutlinedTextField(
                value = textState2,
                onValueChange = {
                    textState2= it
                    when {
                        textState2.text.isEmpty() -> {
                            errorState2 = true
                            errorMessage2 = "City should not blank"
                        }
                        textState2.text.startsWith("0") -> {
                            errorState2 = true
                            errorMessage2 = "City should not start with zero"
                        }
                        else -> {
                            errorState2 = false
                            errorMessage2 = ""
                        }
                    }
                },
                label = {
                    Text(
                        text = if (errorState2) errorMessage2
                        else "Put your city here"
                    )
                },
                modifier = Modifier.fillMaxWidth(),
                isError = errorState2,
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    errorBorderColor = Color(0xFFE30022),
                    errorLabelColor = Color(0xFFFF0800),
                    errorCursorColor = Color(0xFF960018)
                )
            )
        }
    }



    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}