dev.forkhandles.values.validation.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of values4k Show documentation
Show all versions of values4k Show documentation
ForkHandles Value-types library
The newest version!
package dev.forkhandles.values
/**
* Allows validation on values coming in to ensure only legal values construction.
*/
typealias Validation = (T) -> Boolean
val Int.maxLength: Validation get() = { it.length <= this@maxLength }
val Int.minLength: Validation get() = { it.length >= this@minLength }
val Int.exactLength: Validation get() = { it.length == this@exactLength }
val IntRange.length: Validation get() = { [email protected](it.length) }
val String.regex: Validation get() = toRegex().let { v -> { v.matches(it) } }
val > T.maxValue: Validation get() = { it <= this@maxValue }
val > T.minValue: Validation get() = { it >= this@minValue }
val > ClosedRange.between: Validation get() = { [email protected](it) }
val Number.exactValue: Validation get() = { it == this@exactValue }
fun Validation.and(that: Validation): Validation = { this@and(it) && that(it) }
fun Validation.or(that: Validation): Validation = { this@or(it) || that(it) }
operator fun Validation.not(): Validation = { !this@not(it) }
fun Validation.check(value: T) {
require(this(value))
{ "Validation failed for: ${[email protected]}(${value.toString().takeIf { it.isNotBlank() } ?: "\"\""})" }
}