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

commonMain.neat.StringValidatorFactory.kt Maven / Gradle / Ivy

There is a newer version: 3.0.13
Show newest version
@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))) }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy