kvalidation - Validation library for Kotlin
Add to gradle.build.kts
:
repositories {
maven {
url = uri("https://maven.pkg.github.com/hwolf/validation")
}
}
dependencies {
implementation("hwolf.kvalidation:kvalidation-core:0.1.0")
implementation("hwolf.kvalidation:kvalidation-common:0.1.0")
}
Suppose you have a class like this:
data class UserProfile(
val name: String,
val age: Int?,
val password: String?,
val confirmPassword: String?,
val email: String?
)
Using the type-safe DSL you can write a validator:
val userProfileValidator = validator<UserProfile> {
UserProfile::name {
isNotBlank()
hasLength(6, 20)
}
UserProfile::age required {
isGreaterOrEqual(18)
}
UserProfile::password required {
hasLength(8, 40)
}
UserProfile::confirmPassword required {
isEqual(UserProfile::password)
}
UserProfile::email ifPresent {
isEmail()
}
}
and apply it to your data
val invalidUserProfile = UserProfile(
name = "Mr. X",
age = 16,
password = "geheim",
confirmPassword = "anders",
email = "keine Mail")
val result = userProfileValidator.validate(invalidUserProfile)
It's possible to create custom validations:
To create a custom constraint, it's necessary to implement the interface
hwolf.kvalidation.Constraint
, which has these properties:
messageKey
: specifies the name of the key for interpolating messages, the default value is the qualified class name plusmessage
suffix.parameters
: specifies aMap<String, Amy?>
containing the parameters to be replaced in the message, the default values are all class properties, obtained through reflection.
For example:
data class MinLength<T>(val min: T) : Constraint
The validation logic must be within an extension function of
hwolf.kvalidation.ConstraintBuilder<T>.validate.validate(constraint: Constraint, test: (V) -> Boolean)
, where
T
represents the type of the propertyconstraint
the constrainttest
a validation function
For example:
fun <T> ValidationBuilder<T, String>.hasMinLength(min: Int) =
validate(MinLength(min)) { v, _ ->
v.length >= min
}