Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add oneOf, anyOf validations #177

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public class ValidateAll<T>(
override fun toString(): String = "ValidateAll(validation=$validations)"
}

/** Validation that runs multiple validations in sequence and returns all validation errors. */
public class FailFastValidation<T>(
private val validations: List<Validation<T>>,
) : Validation<T> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package io.konform.validation.types

import io.konform.validation.Invalid
import io.konform.validation.Valid
import io.konform.validation.Validation
import io.konform.validation.ValidationResult
import io.konform.validation.flattenNotEmpty
import io.konform.validation.flattenOrValid

public class ValidationAny<T>(
private val validations: List<Validation<T>>,
private val aggregateInvalidResults: (List<Invalid>) -> Invalid = List<Invalid>::flattenNotEmpty,
) : Validation<T> {
override fun validate(value: T): ValidationResult<T> {
val errors = mutableListOf<Invalid>()
for (validation in validations) {
when (val result = validation.validate(value)) {
// We only need 1 validation to succeed the "any" validation
is Valid -> return result
is Invalid -> errors + result
}
}
return errors.flattenOrValid(value)
}

override fun toString(): String = "ValidationAny(validation=$validations)"

private companion object {
private fun defaultAggregateInvalidResults(invalids: List<Invalid>): Invalid {
val combinedErrors =
"all validations failed: ${invalids.flatMap { invalid -> invalid.errors.map { it.message } }}"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package io.konform.validation.validationbuilder

import io.konform.validation.Validation
import io.konform.validation.constraints.maxLength
import io.konform.validation.constraints.minLength
import kotlin.test.Test

class ValidateAnyTest {
@Test
fun validateAny() {
val validation =
Validation<String> {
oneOf(
"must be either length 5 or 10",
{
minLength(5)
maxLength(5)
},
{
minLength(10)
maxLength(10)
},
)
}
}
}
Loading