Data Validation in Kotlin: Library Overview and Practical Examples
Data validation is one of the key aspects of developing reliable applications. In Kotlin, thanks to its concise syntax and powerful type system, the data validation process can be not only efficient but also expressive. In this article, we will look at popular validation libraries, their capabilities, and provide practical code examples.
Why is Validation Needed in Kotlin?
Validation allows you to:
- Ensure data integrity before processing;
- Improve user experience with clear error messages;
- Reduce load on the database and server logic;
- Prevent vulnerabilities related to incorrect input.
Main Approaches to Validation
In Kotlin, three main approaches can be distinguished:
- Annotations — a declarative method, often used with Jakarta Bean Validation (formerly JSR-380).
- DSL Validation — creating validators using a domain-specific language (e.g., Konform).
- Functional Approach — using higher-order functions to compose validation rules.
1. Konform Library
Konform is a lightweight library for data validation in Kotlin that uses DSL. It is ideal for validating objects obtained from JSON or forms.
Usage example:
import konform.*import konform.dsl.*
data class User( val name: String, val email: String, val age: Int)
fun main() { val userValidator = validation<User> { User::name required { minLength(2) hint "Name must be at least 2 characters" maxLength(50) hint "Name must not exceed 50 characters" } User::email required { pattern(Regex("^[\\\\w.-]+@[\\\\w.-]+\\\\.\\\\w{2,}$")) hint "Invalid email" } User::age required { range(18..120) hint "Age must be between 18 and 120" } }
val user = User("A", "invalid-email", 17) val result = userValidator.validate(user) if (result is ValidationResult.Invalid) { result.errors.forEach { (field, errors) -> println("Field '$field': ${errors.joinToString(", ")}") } } else { println("Validation passed!") }}Output:
Field 'name': Name must be at least 2 charactersField 'email': Invalid emailField 'age': Age must be between 18 and 1202. Kotlin Validation Library (KValidation)
KValidation is another popular tool that provides both annotations and DSL. It integrates with Kotlin Serialization and supports nested objects.
Example with annotations:
import io.kvalidation.annotations.*import io.kvalidation.KValidation
@Validatabledata class Address( @NotEmpty(message = "Street cannot be empty") val street: String, @Range(min = 1, max = 9999, message = "House number must be between 1 and 9999") val houseNumber: Int)
@Validatabledata class Person( @NotEmpty(message = "Name is required") @Length(min = 2, max = 100, message = "Name must be between 2 and 100 characters") val name: String, @Email(message = "Invalid email") val email: String, @Valid // nested validation val address: Address)
fun main() { val person = Person("", "test", Address("", 0)) val violations = KValidation.validate(person) violations.forEach { violation -> println("${violatio Also in library
CoreBluetooth for Swift: Complete Guide with Examples
Generating PDF Reports in Rust: The printpdf Library
Task Scheduler in TypeScript: A Detailed Guide to the node-schedule Library
CORS for JavaScript (Node.js): Complete Guide with Examples
Puppeteer for JavaScript (Node.js): Complete Guide with Examples