konform

Konform: Portable validations for Kotlin

License

License

MIT
Categories

Categories

Data ORM
GroupId

GroupId

io.konform
ArtifactId

ArtifactId

konform-metadata
Last Version

Last Version

0.3.0
Release Date

Release Date

Type

Type

jar
Description

Description

konform
Konform: Portable validations for Kotlin
Project URL

Project URL

https://github.com/konform-kt/konform
Source Code Management

Source Code Management

https://github.com/konform-kt/konform.git

Download konform-metadata

How to add to project

<!-- https://jarcasting.com/artifacts/io.konform/konform-metadata/ -->
<dependency>
    <groupId>io.konform</groupId>
    <artifactId>konform-metadata</artifactId>
    <version>0.3.0</version>
</dependency>
// https://jarcasting.com/artifacts/io.konform/konform-metadata/
implementation 'io.konform:konform-metadata:0.3.0'
// https://jarcasting.com/artifacts/io.konform/konform-metadata/
implementation ("io.konform:konform-metadata:0.3.0")
'io.konform:konform-metadata:jar:0.3.0'
<dependency org="io.konform" name="konform-metadata" rev="0.3.0">
  <artifact name="konform-metadata" type="jar" />
</dependency>
@Grapes(
@Grab(group='io.konform', module='konform-metadata', version='0.3.0')
)
libraryDependencies += "io.konform" % "konform-metadata" % "0.3.0"
[io.konform/konform-metadata "0.3.0"]

Dependencies

compile (1)

Group / Artifact Type Version
org.jetbrains.kotlin : kotlin-stdlib-common jar 1.4.32

Project Modules

There are no modules declared in this project.

Build Status Maven Central

Portable validations for Kotlin

  • โœ… Type-safe DSL
  • ๐Ÿ”— Multi-platform support (JVM, JS)
  • ๐Ÿฅ Zero dependencies

Installation

For multiplatform projects:

kotlin {
    sourceSets {
        commonMain {
            dependencies {
                implementation("io.konform:konform:0.3.0")
            }
        }
    }
}

For jvm-only projects add:

dependencies {
    implementation("io.konform:konform:0.3.0")
}

Use

Suppose you have a data class like this:

data class UserProfile(
    val fullName: String,
    val age: Int?
)

Using the Konform type-safe DSL you can quickly write up a validation

val validateUser = Validation<UserProfile> {
    UserProfile::fullName {
        minLength(2)
        maxLength(100)
    }

    UserProfile::age ifPresent {
        minimum(0)
        maximum(150)
    }
}

and apply it to your data

val invalidUser = UserProfile("A", -1)
val validationResult = validateUser(invalidUser)

since the validation fails the validationResult will be of type Invalid and you can get a list of validation errors by indexed access:

validationResult[UserProfile::fullName]
// yields listOf("must have at least 2 characters")

validationResult[UserProfile::age]
// yields listOf("must be at least '0'")

or you can get all validation errors with details as a list:

validationResult.errors
// yields listOf(
//     ValidationError(dataPath=.fullName, message=must have at least 2 characters),
//     ValidationError(dataPath=.age, message=must be at least '0'
// )

In case the validation went through successfully you get a result of type Valid with the validated value in the value field.

val validUser = UserProfile("Alice", 25)
val validationResult = validateUser(validUser)
// yields Valid(UserProfile("Alice", 25))

Advanced use

You can define validations for nested classes and use them for new validations

val ageCheck = Validation<UserProfile> {
    UserProfile::age required {
        minimum(18)
    }
}

val validateUser = Validation<UserProfile> {
    UserProfile::fullName {
        minLength(2)
        maxLength(100)
    }
    
    run(ageCheck)
}

It is also possible to validate nested data classes and properties that are collections (List, Map, etc...)

data class Person(val name: String, val email: String?, val age: Int)

data class Event(
    val organizer: Person,
    val attendees: List<Person>,
    val ticketPrices: Map<String, Double?>
)

val validateEvent = Validation<Event> {
    Event::organizer {
        // even though the email is nullable you can force it to be set in the validation
        Person::email required {
            pattern("[email protected]") hint "Organizers must have a BigCorp email address"
        }
    }

    // validation on the attendees list
    Event::attendees {
        maxItems(100)
    }

    // validation on individual attendees
    Event::attendees onEach {
        Person::name {
            minLength(2)
        }
        Person::age {
            minimum(18) hint "Attendees must be 18 years or older"
        }
        // Email is optional but if it is set it must be valid
        Person::email ifPresent {
            pattern(".+@.+\..+") hint "Please provide a valid email address (optional)"
        }
    }

    // validation on the ticketPrices Map as a whole
    Event::ticketPrices {
        minItems(1) hint "Provide at least one ticket price"
    }

    // validations for the individual entries
    Event::ticketPrices onEach {
        // Tickets may be free in which case they are null
        Entry<String, Double?>::value ifPresent {
            minimum(0.01)
        }
    }
}

Errors in the ValidationResult can also be accessed using the index access method. In case of Iterables and Arrays you use the numerical index and in case of Maps you use the key as string.

// get the error messages for the first attendees age if any
result[Event::attendees, 0, Person::age]

// get the error messages for the free ticket if any
result[Event::ticketPrices, "free"]

Other validation libraries written in Kotlin

Integration with testing libraries

  • Kotest provides various matchers for use with Konform. They can be used in your tests to assert that a given object is validated successfully or fails validation with specific error messages. See usage documentation here.
Author

Niklas Lochschmidt

License

MIT License

io.konform

Versions

Version
0.3.0
0.2.0