Kaval

A POJO validation DSL in Kotlin

License

License

Categories

Categories

KeY Data Data Formats Formal Verification
GroupId

GroupId

io.monkeypatch.kaval
ArtifactId

ArtifactId

kaval-reflect-jvm
Last Version

Last Version

0.4.0
Release Date

Release Date

Type

Type

pom.sha512
Description

Description

Kaval
A POJO validation DSL in Kotlin
Project URL

Project URL

http://github.com/MonkeyPatchIo/kaval
Project Organization

Project Organization

MonkeyPatch
Source Code Management

Source Code Management

https://github.com/MonkeyPatchIo/kaval

Download kaval-reflect-jvm

Dependencies

compile (1)

Group / Artifact Type Version
io.monkeypatch.kaval : kaval-core-jvm jar 0.4.0

runtime (3)

Group / Artifact Type Version
org.jetbrains.kotlin : kotlin-stdlib-jdk8 jar 1.3.72
org.jetbrains.kotlin : kotlin-stdlib-common jar 1.3.72
org.jetbrains.kotlin : kotlin-reflect jar 1.3.72

Project Modules

There are no modules declared in this project.

Kaval Kaval

GitHub Workflow Status GitHub ktlint Awesome Kotlin Badge

This is a Kotlin multi-platform library to validate your model.

Why

The goal is to find the right balance between conciseness, expressiveness, and composability to validate POJO.

Or you can see it as a validation DSL.

Example

We want to validate this model

data class User(
    val firstName: String,
    val lastName: String,
    val address: Address?
)

data class Address(
    val line1: String,
    val line2: String,
    val zipCode: Int,
    val city: String
)

We can validate the Address with these constraints:

  • line1: not blank, and length <= 255
  • line2: length <= 255
  • zipCode: > 0
  • city: not blank
val addressValidator: Validator<Address> =
    reflectValidator {
        Address::line1 { notBlank and maxLength(255) }
        Address::line2 { maxLength(255) }
        Address::zipCode { greaterThan(0) }
        Address::city { notBlank }
    }

And the User with these constraints:

  • firstName: not blank, and length <= 128
  • lastName: length <= 255
  • address: see above
val userValidator: Validator<User> =
    reflectValidator {
        User::firstName { notBlank and maxLength(128) }
        User::lastName { maxLength(255) }
        User::address { nullOr { Address.validator } }
    }

Now we can use the validators:

val user = User(
   firstName = "",
   lastName = "x".repeat(500),
   address = Address(
       line1 = "",
       line2 = "",
       zipCode = -1,
       city = ""
   )
)

val result: ValidationResult = userValidator.validate(user)
println(result)
// Invalid:
//  - [firstName] requires to be not blank
//  - [lastName.length] requires to be lower or equals to 255, got 500
//  - [address.line1] requires to be not blank
//  - [address.zipCode] requires to be greater than 0, got -1
//  - [address.city] requires to be not blank should be Valid

Modules

io.monkeypatch.kaval

Versions

Version
0.4.0
0.2.0