KMM Form Validation
Kotlin Multiplatform library to control and validate forms for Android, iOS, JVM, and browsers via JavaScript and WebAssembly.
Installation
repositories {
mavenCentral()
}
dependencies {
implementation("ru.mobileup:kmm-form-validation:$form_version")
}
Usage
Controls
Controls
are the building blocks for creating validatable forms. The library provides the InputControl
for managing text input values, the CheckControl
for handling boolean input values, and the PickerControl for managing selectable input values, such as dropdowns or pickers.
These controls represent the logical structure of UI elements, allowing for state management and validation logic to be separated from the UI layer.
To ensure proper state management and lifecycle handling, these controls should be instantiated within a state-holder entity, such as a ViewModel or a Decompose component. This ensures that the controls’ state is properly scoped and persists across configuration changes.
Creating an InputControl
InputControl is designed to manage text input with additional features such as text transformation, length restrictions, and keyboard options.
class MyViewModel : ViewModel() {
val nameInput = InputControl(
coroutineScope = viewModelScope,
maxLength = NAME_MAX_LENGTH,
textTransformation = OnlyLettersTextTransformation,
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Words,
imeAction = ImeAction.Next
)
)
}
Using InputControl in UI
You can integrate InputControl with Jetpack Compose TextField by defining a small mapper in your UI layer:
import androidx.compose.foundation.text.KeyboardOptions as ComposeKeyboardOptions
import androidx.compose.ui.text.input.ImeAction as ComposeImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization as ComposeKeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType as ComposeKeyboardType
fun KeyboardOptions.toCompose(): ComposeKeyboardOptions {
return ComposeKeyboardOptions(
capitalization = when (capitalization) {
KeyboardCapitalization.None -> ComposeKeyboardCapitalization.None
KeyboardCapitalization.Characters -> ComposeKeyboardCapitalization.Characters
KeyboardCapitalization.Words -> ComposeKeyboardCapitalization.Words
KeyboardCapitalization.Sentences -> ComposeKeyboardCapitalization.Sentences
},
autoCorrectEnabled = autoCorrect,
keyboardType = when (keyboardType) {
KeyboardType.Text -> ComposeKeyboardType.Text
KeyboardType.Ascii -> ComposeKeyboardType.Ascii
KeyboardType.Email -> ComposeKeyboardType.Email
KeyboardType.Uri -> ComposeKeyboardType.Uri
KeyboardType.Number -> ComposeKeyboardType.Number
KeyboardType.NumberPassword -> ComposeKeyboardType.NumberPassword
KeyboardType.Password -> ComposeKeyboardType.Password
KeyboardType.Phone -> ComposeKeyboardType.Phone
},
imeAction = when (imeAction) {
ImeAction.Default -> ComposeImeAction.Default
ImeAction.None -> ComposeImeAction.None
ImeAction.Search -> ComposeImeAction.Search
ImeAction.Go -> ComposeImeAction.Go
ImeAction.Done -> ComposeImeAction.Done
ImeAction.Next -> ComposeImeAction.Next
ImeAction.Send -> ComposeImeAction.Send
ImeAction.Previous -> ComposeImeAction.Previous
}
)
}
Then use it in your Compose field:
@Composable
fun NameField(inputControl: InputControl) {
val text by inputControl.value.collectAsState()
val enabled by inputControl.enabled.collectAsState()
TextField(
value = text,
onValueChange = inputControl::onValueChange,
enabled = enabled,
keyboardOptions = inputControl.keyboardOptions.toCompose(),
)
}
Creating a CheckControl
CheckControl is designed for managing boolean inputs, such as checkboxes.
class MyViewModel : ViewModel() {
val termsCheckBox = CheckControl(viewModelScope)
}
Using CheckControl in UI
You can integrate CheckControl with Jetpack Compose Checkbox as follows:
@Composable
fun TermsCheckbox(checkControl: CheckControl) {
val checked by checkControl.value.collectAsState()
val enabled by checkControl.enabled.collectAsState()
Checkbox(
checked = checked,
onCheckedChange = checkControl::onValueChange,
enabled = enabled
)
}
Creating a PickerControl
PickerControl<T> is designed for managing selectable inputs, such as dropdowns or pickers.
If the initial value is set to null, it means that no value has been selected yet.
enum class Gender {
Male, Female, Other
}
class MyViewModel : ViewModel() {
val genderPicker = PickerControl<Gender>(viewModelScope)
}
Using PickerControl in UI
You can integrate PickerControl<T> with Jetpack Compose as follows:
@Composable
fun GenderPicker(pickerControl: PickerControl<Gender>) {
val selectedGender by pickerControl.value.collectAsState()
var expanded by remember { mutableStateOf(false) }
Column {
TextButton(onClick = { expanded = true }) {
Text(selectedGender?.name ?: "Select gender")
}
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
Gender.entries.forEach { gender ->
DropdownMenuItem(onClick = {
pickerControl.onValueChange(gender)
expanded = false
}) {
Text(gender.name)
}
}
}
}
}
FormValidation
FormValidator is a utility class designed to manage and validate multiple controls in a form.
It ensures that user inputs meet specific validation criteria and provides dynamic updates on the form’s validation state.
Key Features:
• Validates multiple controls simultaneously
• Supports dynamic validation updates via StateFlow
• Supports both required and optional validation rules
• Can be extended with additional validation features
Creating a FormValidator
To create a FormValidator, use the formValidator DSL inside a CoroutineScope.
enum class ProfileValidationError : ValidationError {
BlankField,
GenderNotSelected,
InvalidEmail,
TermsNotAccepted,
}
val formValidator = viewModelScope.formValidator {
features = listOf(
ValidateOnFocusLost,
RevalidateOnValueChanged,
SetFocusOnFirstInvalidControlAfterValidation
)
input(nameInput, required = false) {
isNotBlank(ProfileValidationError.BlankField)
}
picker(genderPicker) {
isPicked(ProfileValidationError.GenderNotSelected)
}
input(emailInput) {
isNotBlank(ProfileValidationError.BlankField)
regex(
regex = EMAIL_REGEX_PATTERN.toRegex(),
errorMessage = ProfileValidationError.InvalidEmail
)
}
checked(termsCheckBox, ProfileValidationError.TermsNotAccepted)
}
Handling Form validation state
To track form validation, use validationState. This state updates dynamically whenever a field’s value or validation status changes, allowing UI components to react accordingly.
Additionally, you can track whether the form is completely filled isFilledState or contains any errors hasErrorState.
class MyViewModel : ViewModel() {
val formValidator = viewModelScope.formValidator { /*...*/ }
val isFormValid = computed(formValidator.validationState) { it.isValid }
val isLoginButtonEnabled = computed(
formValidator.isFilledState,
formValidator.hasErrorState
) { isFilled, hasError -> isFilled && !hasError }
}
@Composable
fun Screen(viewModel: MyViewModel) {
val isLoginButtonEnabled by viewModel.isLoginButtonEnabled.collectAsState()
Button(
text = "Login",
enabled = isLoginButtonEnabled,
onClick = { /*...*/ }
)
}
• validationState: This state reflects the current validation result of the entire form. It updates whenever any control’s value or validation status changes.
• isFilledState: Tracks whether all required fields are filled. A field is considered filled if it contains valid input or is skipped in validation.
• hasErrorState: This state indicates whether the form contains any validation errors. The form has errors if any control has a non-null error and is not skipped in validation.
Manual Form Validation
The validate() method allows you to manually trigger form validation, ensuring that all input fields meet their validation criteria before proceeding with an action.
Unlike reactive validation tracking, which only observes changes without displaying errors, this method performs validation and immediately updates the fields with error messages.
This makes it useful for scenarios where user input needs to be explicitly validated and reflected in the UI.
class MyViewModel : ViewModel() {
val formValidator = viewModelScope.formValidator { /*...*/ }
fun onLoginClick() {
if (formValidator.validate().isValid) {
/*perform action*/
} else {
/*show error*/
}
}
}
Advanced Usage
For advanced usage, you can refer to the Sample.
The sample demonstrates how to integrate InputControl, CheckControl, and PickerControl<T> in a real-world scenario using the Decompose library.
License