Simplify Form Validation using Kotlin Flow on Android | Part 2

Ashish Suthar
3 min readNov 7, 2022

--

This article will demonstrate the practical use of the concept implemented in part 1.

In part 1, We had implemented

  1. FormField — Base class for a different type of form fields
  2. FormFieldText — FormField implementation for text type fields
  3. Username field — For learning how to declare a field in activity (or fragments) with validation rules using FormFieldText class

Last time we used only a single field to show working on FormFieldText class. Now we will use five fields (Username, Email, Phone Number, Password, and Confirm Password) with different validation rules.

“Form is a collection of fields”

To create large forms, We will need to create a list of FormFields.

Form created using FormFields

In the above code, you can see we have created a list of fields. Its name is formFields, You can also name it “form”.

Each form field is derived from FormField class, So the above-given list will be a list of FormFields indirectly.

For executing validate method of each form field, We need some extension functions.

Other helpful extension functions are given below for performing actions on the form.

We have all things we need for creating forms. Let’s use them in our example activity code.

After implementing the above code, We will have the below form.

Validating a form using FormField on Android

Bonus tips

How to exclude a field from validation?

You can set the visibility of the field by using the isVisible property of FormField. When the field is hidden, It will be excluded from validation.

fieldUsername.isVisible = false

How to validate all fields at once?

By default validateAll parameter of validate method is false. So it will validate fields from top to bottom. You can change that behavior by setting it to true.

formFields.validate(validateAll = true)

How to perform asynchronous validation?

The validation block of FormField is a suspendable function. So you can launch coroutines for asynchronous validation. For example, You can check username availability by calling API in the validation block.

Asynchronous validation using FormField

That’s all!

I have used the above technique in one of my professional projects. I feel you may find it helpful and save you from hours of struggle. That’s why I have shared my experience.

If you want support for more advanced form validation techniques or need support for implementing other types of FormFields (Date, Time, List, CheckBox, or any custom form fields) Contact me at asissuthar@gmail.com

There are a lot of possibilities with the above article, Your suggestions are much appreciated!

Thanks for reading!

--

--