From 7fb9b8eb3bb548653ed21c3df5cfa30da353ca0e Mon Sep 17 00:00:00 2001 From: David Hoepelman <992153+dhoepelman@users.noreply.github.com> Date: Mon, 11 Nov 2024 22:12:03 +0100 Subject: [PATCH] Add Validation.ifPresent and Validation.required (#164) --- api/konform.api | 2 ++ src/commonMain/kotlin/io/konform/validation/Validation.kt | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/api/konform.api b/api/konform.api index f0ddaa0..816c64b 100644 --- a/api/konform.api +++ b/api/konform.api @@ -98,6 +98,8 @@ public abstract interface class io/konform/validation/ValidationErrors : java/ut public final class io/konform/validation/ValidationKt { public static final fun flatten (Ljava/util/List;)Lio/konform/validation/Validation; + public static final fun ifPresent (Lio/konform/validation/Validation;)Lio/konform/validation/Validation; + public static final fun required (Lio/konform/validation/Validation;)Lio/konform/validation/Validation; } public abstract class io/konform/validation/ValidationResult { diff --git a/src/commonMain/kotlin/io/konform/validation/Validation.kt b/src/commonMain/kotlin/io/konform/validation/Validation.kt index 2067217..fcc8fae 100644 --- a/src/commonMain/kotlin/io/konform/validation/Validation.kt +++ b/src/commonMain/kotlin/io/konform/validation/Validation.kt @@ -1,6 +1,7 @@ package io.konform.validation import io.konform.validation.types.EmptyValidation +import io.konform.validation.types.NullableValidation import io.konform.validation.types.ValidateAll public interface Validation { @@ -20,3 +21,9 @@ public fun List>.flatten(): Validation = 1 -> first() else -> ValidateAll(this) } + +/** Run a validation only if the actual value is not-null. */ +public fun Validation.ifPresent(): Validation = NullableValidation(required = false, validation = this) + +/** Require a nullable value to actually be present. */ +public fun Validation.required(): Validation = NullableValidation(required = true, validation = this)