All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dev.forkhandles.values.validation.kt Maven / Gradle / Ivy

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() } ?: "\"\""})" }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy