Member-only story
How to Validate Fields Using Jetpack Compose in Android
Check if the email and password fields are correct and display the message accordingly
In this article, we’re going to learn how to validate input data when a user submits a form and shows a custom error message. Validations in this article cover: empty submissions, valid email checks, and character length checks, radio group selection checks, etc.
Introduction
Jetpack Compose is one of the recent attempts by Google to make it easy for Android developers to build UI.
“Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs.” — Android Developers
Jetpack Compose is stable version 1.0 is released recently, which means it’s production-ready. So it would be a great time to learn how to work with the next-generation UI kit for Android development.
You will need to install Android Studio — Arctic Fox (2020.3.1) version to use the Jetpack Compose.
Prerequisites
Before going any further, you must have basic knowledge of how to work with Jetpack Compose. If you’re new to Compose, I highly recommend going through the following articles:
Empty and Invalid Email Validation
Empty Validation
Let’s start with a simple empty field check. First, we need to create an input text field that updates values while the user types. As we know jetpack compose is a state-based UI, so we need to create a mutableStateOf
string and a lambda that updates the string. Have a look:
@Composable
fun ValidationsComposble(){
var name by remember { mutableStateOf("") }
val nameTextUpdate = { data : String ->
name = data
}
}
Next, we need to create another composable function to build the UI and it takes the mutableStateOf
string and update function as inputs…