You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
data classMyUIState(
// This is the value of the inputvalrequiredInput:String? = null,
// This is the last result of the validation and will be used to display a possible error statevarrequiredInputValidationResult:MutableState<ValidationResult?> = mutableStateOf(null)
) {
// This is a validator with the rules on which you want to validateprivateval validator =TextValidator.withRules(RequiredRule()) // Takes a vararg of rules so you can add as many as you want// This is a method that will be called in the LaunchEffect of the composable when the dependency changes (in this case "requiredInput") // Has to be called in the LaunchedEffect, since we need the context to validate the inputfunvalidateRequiredInput(context:Context) {
if(requiredInput ==null) return// If the input is null, we don't want to validate it// Perform the validation and update the result// .value is used to update the MutableState
requiredInputValidationResult.value = validator.validate(context, requiredInput)
}
}
Composable
Handle validating the inputs
val context =LocalContext.current
LaunchedEffect(uiState.requiredInput) {
uiState.validateRequiredInput(context)
}
Displaying the errorMessage (e.g.: in a TextField)
MyTextField(
error = uiState.requiredInputValidationResult.errorMessage() // Will be your error message if the validation fails
)
Validating all inputs (e.g: for a button enabled state)
val areInputsValid by remember {
derivedStateOf {
uiState.requiredInputValidationResult.isValid() ==true// More validation checks can be added// e.g.: && uiState.otherInputValidationResult?.isValid() == true && ...
}
}
Button(
enabled = areInputsValid
)
Building your own validation rules
classMyCustomRule(
overridevalerrorMessage: (context: Context) ->String = { context -> context.getString(R.string.error_message) }
): TextValidationRule {
overrideval validationRule: (String) ->Boolean= {
// Your validation logic// e.g.: input.length > 5// Return true if the input is valid
}
}
About
A simple yet flexible Validation Library for Jetpack Compose