commonMain.neat.StringValidatorFactory.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of neat-validation-jvm Show documentation
Show all versions of neat-validation-jvm Show documentation
A collection library that is built with interoperability in mind
@file:Suppress("NOTHING_TO_INLINE")
package neat
import kotlin.reflect.KProperty
fun string(label: String = "unnamed"): Validators = custom(label)
fun string(name: KProperty) = validator(name.name)
@PublishedApi
internal object StringKey {
private const val root = "neat.string"
const val LENGTH = "$root.length"
const val MIN = "$root.min"
const val MAX = "$root.max"
const val NOT_BLANK = "$root.not.blank"
}
fun > V.length(
value: Int,
message: (value: String) -> String = { "$label should have $value character(s), but has ${it.length} character(s) instead" }
) = append(StringKey.LENGTH, value) { if (it.length == value) Valid(it) else Invalid(it, listOf(message(it))) }
inline val Validator.length: Int? get() = int(StringKey.LENGTH)
fun > V.min(
value: Int,
message: (String) -> String = { "$label should have more than $value character(s), but has ${it.length} character(s) instead" }
) = append(StringKey.MIN, value) {
if (it.length >= value) Valid(it) else Invalid(it, listOf(message(it)))
}
inline val Validator.min get() = int(StringKey.MIN)
fun > V.max(
value: Int,
message: (String) -> String = { "$label should have less than $value character(s), but has ${it.length} character(s) instead" }
) = append(StringKey.MAX, value) {
if (it.length <= value) Valid(it) else Invalid(it, listOf(message(it)))
}
inline val Validator.max get() = int(StringKey.MAX)
fun > V.notBlank(
message: (String) -> String = { "$label is required to not be empty but it was" }
) = append(StringKey.NOT_BLANK) { if (it.isNotBlank()) Valid(it) else Invalid(it, listOf(message(it))) }