Description
I am using yavi to validate the properties of a Kotlin class (not arguments to a function). For some of the constraints, it is nice to use the Kotlin DSL syntax. For others (e.g., property of type List that I want to enforce constraints on each element of the list, or where I want to use a custom error message for a constraint), I can't use the Kotlin DSL.
Is there any way to combine the two validators and then call validate once? Or can I call validate on both validators and then combine the results?
Here is a simple example of the two styles of validators:
data class NestedClass(
val id: String,
val listOfString: List<String>,
)
val validatorUsingKotlinDsl = validator<NestedClass> {
NestedClass::id { notBlank() }
NestedClass::listOfString { notEmpty() }
}
val validatorNotUsingKotlinDsl = ValidatorBuilder.of<NestedClass>()
.forEach(NestedClass::listOfString, "listOfString") { cc ->
cc.constraint(String::toString, "") { it.notBlank() }
}
.build()
// some instances to test
val validNestedClass = NestedClass("valid", listOf("valid"))
val invalidNestedClassOne = NestedClass("valid", listOf(""))
val invalidNestedClassTwo = NestedClass("", listOf("valid"))
val invalidNestedClassThree = NestedClass("valid", emptyList())
// how to combine validatorUsingKotlinDsl and validatorNotUsingKotlinDsl before calling validate
// OR how to combine the results of running validatorUsingKotlinDsl.validate(instanceToTest) and validatorNotUsingKotlinDsl.validate(instanceToTest) separately
And am I correct that there is no way to provide a custom error message or message format using Kotlin DSL?
Also, I was experimenting with creating a single value validator and using liftList
to apply it to a list of Strings. It works, to call validate on a list of strings, but I could not figure out how to use it as a constraint for a property that is of type List.
val listOfStringElementValidator = StringValidatorBuilder
.of("") { it.notBlank() }
.build()
val validListOfString = listOf("valid")
val invalidListOfString = listOf("")
// this works as expected
listOfStringElementValidator.liftList().validate(validListOfString).isValid // true
listOfStringElementValidator.liftList().validate(invalidListOfString).isValid // false
// but is there a way to reference listOfStringElementValidator or the "lifted" version of it as part of a validator for a parent class that contains a property that is of type List<String>?