Validating User Input in Kotlin: A Guide to Adding Validation to a New Transaction

Kacper Bąk
2 min readFeb 11, 2023
Photo by David Pupaza on Unsplash

While sitting down with my morning coffee to work on my own project, I came across a problem such that when adding a new transaction, the fields that were supposed to accept data were being handled incorrectly. Somewhat related to my code refactoring.

I had to figure out how to add validation so that the user could not crash the application.

So I turned on the debugger and traced my code specifically, catching the most significant places where the application was crashing.

        // do transaction and store it in realtime database, but first check if fields are filled
binding.fab.setOnClickListener { view ->
doTransaction(view)
}

}

private fun doTransaction(view: View) {
// get data from edit text
val amount = binding.root.findViewById<AppCompatEditText>(R.id.amount).text.toString().toDouble()
val receiver = binding.root.findViewById<AppCompatEditText>(R.id.receiver).text.toString()
val description = binding.root.findViewById<AppCompatEditText>(R.id.description).text.toString()

The code that was flawed and most striking to me was this. Even at first glance you can see that the validation is missing here, the fix was quite simple, all you had to do was add the relevant logic responsible for validation, which in my opinion is best extracted into a separate function.

        binding.fab.setOnClickListener { view ->
if (validateInput()) {
doTransaction(view)
}
}
}

private fun validateInput(): Boolean {
val amountEditText = binding.root.findViewById<AppCompatEditText>(R.id.amount)
val receiverEditText = binding.root.findViewById<AppCompatEditText>(R.id.receiver)
val descriptionEditText = binding.root.findViewById<AppCompatEditText>(R.id.description)

var isValid = true

if (amountEditText.text.isEmpty()) {
amountEditText.error = "Amount is required."
isValid = false
}

if (receiverEditText.text.isEmpty()) {
receiverEditText.error = "Receiver is required."
isValid = false
}

if (descriptionEditText.text.isEmpty()) {
descriptionEditText.error = "Description is required."
isValid = false
}

return isValid
}

private fun doTransaction(view: View) {
// get data from edit text
val amount = binding.root.findViewById<AppCompatEditText>(R.id.amount).text.toString().toDouble()
val receiver = binding.root.findViewById<AppCompatEditText>(R.id.receiver).text.toString()
val description = binding.root.findViewById<AppCompatEditText>(R.id.description).text.toString()

In the validateInput function, the input fields are retrieved and checked if they are empty. If any of the fields are empty, an error message is set and the isValid flag is set to false. The function returns isValid indicating whether all the input fields are filled or not. If the input fields are valid, the doTransaction function is called.

Source code: https://github.com/53jk1/ExchangeableToken

--

--