Skip to content

Commit

Permalink
add val ValidationResult<T>.isValid (#113)
Browse files Browse the repository at this point in the history
  • Loading branch information
jillesvangurp authored May 22, 2024
1 parent 44a8e4e commit f1afaf8
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ public sealed class ValidationResult<out T> {
}

public abstract val errors: List<ValidationError>

/**
* Returns true if the [ValidationResult] is [Valid].
*/
public val isValid: Boolean =
when (this) {
is Invalid -> false
is Valid -> true
}
}

public data class Invalid(
Expand Down
46 changes: 32 additions & 14 deletions src/commonTest/kotlin/io/konform/validation/ValidationResultTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,33 @@ import io.konform.validation.jsonschema.minLength
import io.konform.validation.jsonschema.pattern
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class ValidationResultTest {
@Test
fun singleValidation() {
val validation =
Validation<Person> {
Person::name {
minLength(1)
}
private val validation =
Validation {
Person::name {
minLength(1)
}

Person::addresses onEach {
Address::city {
City::postalCode {
minLength(4)
maxLength(5)
pattern("\\d{4,5}") hint ("must be a four or five digit number")
}
Person::addresses onEach {
Address::city {
City::postalCode {
minLength(4)
maxLength(5)
pattern("\\d{4,5}") hint ("must be a four or five digit number")
}
}
}
}

@Test
fun singleValidation() {
val result = validation(Person("", addresses = listOf(Address(City("", "")))))

assertFalse(result.isValid)

assertEquals(3, result.errors.size)
val (firstError, secondError, thirdError) = result.errors

Expand All @@ -40,6 +45,19 @@ class ValidationResultTest {
assertEquals("must be a four or five digit number", thirdError.message)
}

@Test
fun positiveValidation() {
val result =
validation(
Person(
name = "Jane Doe",
addresses = listOf(Address(City("10115", "Berlin"))),
),
)

assertTrue(result.isValid)
}

private data class Person(val name: String, val addresses: List<Address>)

private data class Address(val city: City)
Expand Down

0 comments on commit f1afaf8

Please sign in to comment.