Skip to main content
When the class is yours, its rules belong next to its fields. Implement Validatable and return the rules from validation(), written with the validation { } block:
Account.kt
Inside the block, ::username is the property of the object being validated. Each rule starts from a property, says what null means for it (required, ifPresent or forbidden), and lists the constraints of its value in the block that follows. Several constraints in one block are all checked, in order.

Checking the rules

A Validatable has four ways to run its rules. They run the same rules and differ only in how they wait and how they answer:
Every rule runs: one object reports every broken rule at once, in the order the rules are declared. When a rule only makes sense after another, failFast stops at the first failure.
The suspending functions are the main path: rules can call suspend functions. The blocking ones exist for code that cannot suspend, such as a plain servlet or a main function.

Conditions are plain Kotlin

The block is ordinary Kotlin code that runs when the object is validated, so the values of the object are there to read. A rule that applies only sometimes is an if or a when:
There are no validation groups and no class-level annotations: the condition is written where it applies.

The configuration of one call

Each of the four functions takes an optional Validity, a configuration for that call only: other messages, or another clock.

Rules beside the class

For a class that is not yours, or rules that belong elsewhere.

Reading the result

ValidationResult, Violation and what each field holds.