The ValidationContext is the central hub for managing validation logic within a form or a group of inputs. It tracks multiple Validator instances, maintains a global valid state, and provides a decorationProvider to define how errors are visually represented on UI nodes.
Key Capabilities
- Register Validators: Use
addValidator to attach validation logic to properties or UI controls. - Global State: Access the
valid property to determine if the entire context is currently valid. - Manual Validation: Trigger validation for all registered fields or specific ones using
validate(). - Custom Decoration: Override
decorationProvider to change how error messages (like tooltips or icons) are displayed.
Validation Triggers
Control when validation occurs using ValidationTrigger:
ValidationTrigger.OnBlur: Validates when the associated node loses focus.ValidationTrigger.OnChange(delay: Long): Validates when the property changes. You can specify a delay in milliseconds to debounce rapid input.ValidationTrigger.None: No automatic validation occurs.
Severity Levels
Validators return a ValidationMessage with one of the following severities:
ValidationSeverity.Error (Invalidates the field)ValidationSeverity.WarningValidationSeverity.InfoValidationSeverity.Success
Note: A field is considered valid if the validator returns null or a message with a severity other than Error.
val context = ValidationContext()
// Add a validator to a property
context.addValidator(textField, myProperty) { value ->
if (value.isNullOrBlank()) error("Field cannot be empty") else null
}
// Check if the whole form is valid
if (context.valid) {
// Proceed with submission
}