Configuration
Validators are instantiated with a default configuration. You can override some values to your needs by providing a Configuration
when instantiating your validator, using Validator<T>(CONFIGURATION_INSTANCE) { ... }
.
Here's an example where we override the default violation message and the root path:
val customConfig = Configuration {
defaultViolationMessage = "The field contains an invalid value"
rootPath("custom", "root", "path")
}
val validateString = Validator<String>(customConfig) {
length.constrain { false }
}
when (val result = validateString("foo")) {
is ValidationResult.Success -> {}
is ValidationResult.Failure -> {
for ((message, path) in result.violations) {
println("$path: $message")
}
}
}
The output is the following:
[custom, root, path, length]: The field contains an invalid value
Without providing any custom configuration, it would have been:
[length]: The value is invalid.
Last modified: 19 December 2024