{"id":13428846,"url":"https://github.com/valiktor/valiktor","last_synced_at":"2026-01-11T17:46:04.939Z","repository":{"id":38870576,"uuid":"127146179","full_name":"valiktor/valiktor","owner":"valiktor","description":"Valiktor is a type-safe, powerful and extensible fluent DSL to validate objects in Kotlin","archived":false,"fork":false,"pushed_at":"2021-12-16T09:04:46.000Z","size":2843,"stargazers_count":430,"open_issues_count":33,"forks_count":35,"subscribers_count":8,"default_branch":"master","last_synced_at":"2024-10-27T06:39:18.191Z","etag":null,"topics":["dsl","kotlin","kotlin-dsl","kotlin-library","validation","validation-library","validations"],"latest_commit_sha":null,"homepage":"","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/valiktor.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-03-28T13:40:48.000Z","updated_at":"2024-10-08T17:02:30.000Z","dependencies_parsed_at":"2022-07-14T04:10:43.559Z","dependency_job_id":null,"html_url":"https://github.com/valiktor/valiktor","commit_stats":null,"previous_names":[],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/valiktor%2Fvaliktor","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/valiktor%2Fvaliktor/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/valiktor%2Fvaliktor/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/valiktor%2Fvaliktor/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/valiktor","download_url":"https://codeload.github.com/valiktor/valiktor/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243815597,"owners_count":20352195,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dsl","kotlin","kotlin-dsl","kotlin-library","validation","validation-library","validations"],"created_at":"2024-07-31T01:01:06.609Z","updated_at":"2026-01-11T17:46:04.884Z","avatar_url":"https://github.com/valiktor.png","language":"Kotlin","readme":"![Valiktor](docs/logo.png)\n\n\u003e Valiktor is a type-safe, powerful and extensible fluent DSL to validate objects in Kotlin.\n\n[![Build Status](https://travis-ci.org/valiktor/valiktor.svg?branch=master)](https://travis-ci.org/valiktor/valiktor)\n[![Build status](https://ci.appveyor.com/api/projects/status/github/valiktor/valiktor?branch=master\u0026svg=true)](https://ci.appveyor.com/project/rodolphocouto/valiktor)\n[![Coverage Status](https://codecov.io/gh/valiktor/valiktor/branch/master/graph/badge.svg)](https://codecov.io/gh/valiktor/valiktor)\n[![Quality Status](https://api.codacy.com/project/badge/Grade/1826622893374838856952b9c013793a)](https://www.codacy.com/app/rodolphocouto/valiktor?utm_source=github.com\u0026amp;utm_medium=referral\u0026amp;utm_content=valiktor/valiktor\u0026amp;utm_campaign=Badge_Grade)\n[![Code Style](https://img.shields.io/badge/code%20style-%E2%9D%A4-FF4081.svg)](https://ktlint.github.io)\n[![Maven Central](https://img.shields.io/maven-central/v/org.valiktor/valiktor-core.svg)](https://search.maven.org/search?q=g:org.valiktor)\n[![Apache License](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](LICENSE)\n\n## Installation\n\n![Gradle](docs/gradle.png)\n\n```groovy\nimplementation 'org.valiktor:valiktor-core:0.12.0'\n```\n\n![Gradle](docs/gradle.png) (Kotlin DSL)\n\n```kotlin\nimplementation(\"org.valiktor:valiktor-core:0.12.0\")\n```\n\n![Maven](docs/maven.png) \n\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003eorg.valiktor\u003c/groupId\u003e\n  \u003cartifactId\u003evaliktor-core\u003c/artifactId\u003e\n  \u003cversion\u003e0.12.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n* For install other modules, see [Modules](#modules).\n\n## Getting Started\n\n```kotlin\ndata class Employee(val id: Int, val name: String, val email: String) {\n    init {\n        validate(this) {\n            validate(Employee::id).isPositive()\n            validate(Employee::name).hasSize(min = 3, max = 80)\n            validate(Employee::email).isNotBlank().isEmail()\n        }\n    }\n}\n```\n\n### How it works\n\nThe main function `org.valiktor.validate` expects an object and an anonymous function that will validate it. Within this, it's possible to validate the object properties by calling `org.valiktor.validate` with the respective property as parameter. Thanks to Kotlin's powerful reflection, it's type safe and very easy, e.g.: `Employee::name`. There are many validation constraints (`org.valiktor.constraints.*`) and extension functions (`org.valiktor.functions.*`) for each data type. For example, to validate that the employee's name cannot be empty: `validate(Employee::name).isNotEmpty()`.\n\nAll the `validate` functions are evaluated and if any constraint is violated, a `ConstraintViolationException` will be thrown with a set of `ConstraintViolation` containing the property, the invalid value and the violated constraint.\n\nFor example, consider this data class:\n\n```kotlin\ndata class Employee(val id: Int, val name: String)\n```\n\nAnd this invalid object:\n\n```kotlin\nval employee = Employee(id = 0, name = \"\")\n```\n\nNow, let's validate its `id` and `name` properties and handle the exception that will be thrown by printing the property name and the violated constraint:\n\n```kotlin\ntry {\n    validate(employee) {\n        validate(Employee::id).isPositive()\n        validate(Employee::name).isNotEmpty()\n    }\n} catch (ex: ConstraintViolationException) {\n    ex.constraintViolations\n        .map { \"${it.property}: ${it.constraint.name}\" }\n        .forEach(::println)\n}\n```\n\nThis code will return:\n\n```\nid: Greater\nname: NotEmpty\n```\n\nSee the [sample](valiktor-samples/valiktor-sample-hello-world)\n\n### Nested object properties\n\nValiktor can also validate nested objects and properties recursively.\n\nFor example, consider these data classes:\n\n```kotlin\ndata class Employee(val company: Company)\ndata class Company(val city: City)\ndata class City(val name: String)\n```\n\nAnd this invalid object:\n\n```kotlin\nval employee = Employee(company = Company(city = City(name = \"\")))\n```\n\nNow, let's validate the property `name` of `City` object and handle the exception that will be thrown by printing the property name and the violated constraint:\n\n```kotlin\ntry {\n    validate(employee) {\n        validate(Employee::company).validate {\n            validate(Company::city).validate {\n                validate(City::name).isNotEmpty()\n            }\n        }\n    }\n} catch (ex: ConstraintViolationException) {\n    ex.constraintViolations\n        .map { \"${it.property}: ${it.constraint.name}\" }\n        .forEach(::println)\n}\n```\n\nThis code will return:\n\n```\ncompany.city.name: NotEmpty\n```\n\nSee the [sample](valiktor-samples/valiktor-sample-nested-properties)\n\n### Array and collection properties\n\nArray and collection properties can also be validated, including its elements.\n\nFor example, consider these data classes:\n\n```kotlin\ndata class Employee(val dependents: List\u003cDependent\u003e)\ndata class Dependent(val name: String)\n```\n\nAnd this invalid object:\n\n```kotlin\nval employee = Employee(\n    dependents = listOf(\n        Dependent(name = \"\"), \n        Dependent(name = \"\"), \n        Dependent(name = \"\")\n    )\n)\n```\n\nNow, let's validate the property `name` of all `Dependent` objects and handle the exception that will be thrown by printing the property name and the violated constraint:\n\n```kotlin\ntry {\n    validate(employee) {\n        validate(Employee::dependents).validateForEach {\n            validate(Dependent::name).isNotEmpty()\n        }\n    }\n} catch (ex: ConstraintViolationException) {\n    ex.constraintViolations\n        .map { \"${it.property}: ${it.constraint.name}\" }\n        .forEach(::println)\n}\n```\n\nThis code will return:\n\n```\ndependents[0].name: NotEmpty\ndependents[1].name: NotEmpty\ndependents[2].name: NotEmpty\n```\n\nSee the [sample](valiktor-samples/valiktor-sample-collections)\n\n### Internationalization\n\nValiktor provides a decoupled internationalization, that allows to maintain the validation logic in the core of the application and the internationalization in another layer, such as presentation or RESTful adapter. This guarantees some design principles proposed by Domain-Driven Design or Clean Architecture, for example.\n\nThe internationalization works by converting a collection of `ConstraintViolation` into a collection of `ConstraintViolationMessage` through the extension function `org.valiktor.i18n.mapToMessage` by passing the following parameters:\n\n* `baseName`: specifies the prefix name of the message properties, the default value is `org/valiktor/messages`.\n* `locale`: specifies the `java.util.Locale` of the message properties, the default value is the default locale of the application.\n\nFor example:\n\n```kotlin\ntry {\n    validate(employee) {\n        validate(Employee::id).isPositive()\n        validate(Employee::name).isNotEmpty()\n    }\n} catch (ex: ConstraintViolationException) {\n    ex.constraintViolations\n        .mapToMessage(baseName = \"messages\", locale = Locale.ENGLISH)\n        .map { \"${it.property}: ${it.message}\" }\n        .forEach(::println)\n}\n```\n\nThis code will return:\n\n```\nid: Must be greater than 1\nname: Must not be empty\n```\n\n#### Supported locales\n\nCurrently the following locales are natively supported by Valiktor:\n\n* `ca` (Catalan)\n* `de` (German)\n* `en` (English)\n* `es` (Spanish)\n* `ja` (Japanese)\n* `pt_BR` (Portuguese/Brazil)\n\n#### Customizing a message\n\nAny constraint message of any language can be overwritten simply by adding the message key into your message bundle file. Generally the constraint key is the qualified class name plus `message` suffix, e.g.: `org.valiktor.constraints.NotEmpty.message`.\n\n#### Message formatters\n\nSome constraints have parameters of many types and these parameters need to be interpolated with the message. The default behavior of Valiktor is to call the object `toString()` function, but some data types require specific formatting, such as date/time and monetary values. So for these cases, there are custom formatters (`org.valiktor.i18n.formatters.*`).\n\nFor example:\n\n```kotlin\ntry {\n    validate(employee) {\n        validate(Employee::dateOfBirth).isGreaterThan(LocalDate.of(1950, 12, 31))\n    }\n} catch (ex: ConstraintViolationException) {\n    ex.constraintViolations\n        .mapToMessage(baseName = \"messages\")\n        .map { \"${it.property}: ${it.message}\" }\n        .forEach(::println)\n}\n```\n\nWith `en` as the default locale, this code will return:\n\n```\ndateOfBirth: Must be greater than Dec 31, 1950\n```\n\nWith `pt_BR` as the default locale, this code will return:\n\n```\ndateOfBirth: Deve ser maior que 31/12/1950\n```\n\nCurrently the following types have a custom formatter supported by Valiktor:\n\n| Type                          | Formatter                                                                                                                                          |\n| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `kotlin.Any`                  | [org.valiktor.i18n.formatters.AnyFormatter](valiktor-core/src/main/kotlin/org/valiktor/i18n/formatters/AnyFormatter.kt)                            |\n| `kotlin.Array`                | [org.valiktor.i18n.formatters.ArrayFormatter](valiktor-core/src/main/kotlin/org/valiktor/i18n/formatters/ArrayFormatter.kt)                        |\n| `kotlin.Number`               | [org.valiktor.i18n.formatters.NumberFormatter](valiktor-core/src/main/kotlin/org/valiktor/i18n/formatters/NumberFormatter.kt)                      |\n| `kotlin.collections.Iterable` | [org.valiktor.i18n.formatters.IterableFormatter](valiktor-core/src/main/kotlin/org/valiktor/i18n/formatters/IterableFormatter.kt)                  |\n| `java.util.Calendar`          | [org.valiktor.i18n.formatters.CalendarFormatter](valiktor-core/src/main/kotlin/org/valiktor/i18n/formatters/CalendarFormatter.kt)                  |\n| `java.util.Date`              | [org.valiktor.i18n.formatters.DateFormatter](valiktor-core/src/main/kotlin/org/valiktor/i18n/formatters/DateFormatter.kt)                          |\n| `java.time.LocalDate`         | [org.valiktor.i18n.formatters.LocalDateFormatter](valiktor-javatime/src/main/kotlin/org/valiktor/i18n/formatters/LocalDateFormatter.kt)            |\n| `java.time.LocalTime`         | [org.valiktor.i18n.formatters.LocalTimeFormatter](valiktor-javatime/src/main/kotlin/org/valiktor/i18n/formatters/LocalTimeFormatter.kt)            |\n| `java.time.LocalDateTime`     | [org.valiktor.i18n.formatters.LocalDateTimeFormatter](valiktor-javatime/src/main/kotlin/org/valiktor/i18n/formatters/LocalDateTimeFormatter.kt)    |\n| `java.time.OffsetTime`        | [org.valiktor.i18n.formatters.OffsetTimeFormatter](valiktor-javatime/src/main/kotlin/org/valiktor/i18n/formatters/OffsetTimeFormatter.kt)          |\n| `java.time.OffsetDateTime`    | [org.valiktor.i18n.formatters.OffsetDateTimeFormatter](valiktor-javatime/src/main/kotlin/org/valiktor/i18n/formatters/OffsetDateTimeFormatter.kt)  |\n| `java.time.ZonedDateTime`     | [org.valiktor.i18n.formatters.ZonedDateTimeFormatter](valiktor-javatime/src/main/kotlin/org/valiktor/i18n/formatters/ZonedDateTimeFormatter.kt)    |\n| `javax.money.MonetaryAmount`  | [org.valiktor.i18n.formatters.MonetaryAmountFormatter](valiktor-javamoney/src/main/kotlin/org/valiktor/i18n/formatters/MonetaryAmountFormatter.kt) |\n| `org.joda.time.DateTime`      | [org.valiktor.i18n.formatters.DateTimeFormatter](valiktor-jodatime/src/main/kotlin/org/valiktor/i18n/formatters/DateTimeFormatter.kt)              |\n| `org.joda.time.LocalDate`     | [org.valiktor.i18n.formatters.LocalDateFormatter](valiktor-jodatime/src/main/kotlin/org/valiktor/i18n/formatters/LocalDateFormatter.kt)            |\n| `org.joda.time.LocalTime`     | [org.valiktor.i18n.formatters.LocalTimeFormatter](valiktor-jodatime/src/main/kotlin/org/valiktor/i18n/formatters/LocalTimeFormatter.kt)            |\n| `org.joda.time.LocalDateTime` | [org.valiktor.i18n.formatters.LocalDateTimeFormatter](valiktor-jodatime/src/main/kotlin/org/valiktor/i18n/formatters/LocalDateTimeFormatter.kt)    |\n| `org.joda.money.Money`        | [org.valiktor.i18n.formatters.MoneyFormatter](valiktor-jodamoney/src/main/kotlin/org/valiktor/i18n/formatters/MoneyFormatter.kt)                   |\n| `org.joda.money.BigMoney`     | [org.valiktor.i18n.formatters.BigMoneyFormatter](valiktor-jodamoney/src/main/kotlin/org/valiktor/i18n/formatters/BigMoneyFormatter.kt)             |\n\n#### Creating a custom formatter\n\nCreating a custom formatter is very simple, just implement the interface `org.valiktor.i18n.Formatter`, like this:\n\n```kotlin\nobject CustomFormatter : Formatter\u003cCustom\u003e {\n    override fun format(value: Custom, messageBundle: MessageBundle) = value.toString()\n}\n```\n\nThen add it to the list of formatters (`org.valiktor.i18n.Formatters`):\n\n```kotlin\nFormatters[Custom::class] = CustomFormatter\n```\n\nIt's also possible to use the SPI (Service Provider Interface) provided by Valiktor using the `java.util.ServiceLoader` to discover the formatters automatically without adding them to the list programmatically. For this approach, it's necessary to implement the interface `org.valiktor.i18n.FormatterSpi`, like this:\n\n```kotlin\nclass CustomFormatterSpi : FormatterSpi {\n\n    override val formatters = setOf(\n        Custom::class to CustomFormatter\n    )\n}\n```\n\nThen create a file `org.valiktor.i18n.FormatterSpi` within the directory `META-INF.services` with the content:\n\n```\ncom.company.CustomFormatterSpi\n```\n\nSee the [sample](valiktor-samples/valiktor-sample-custom-formatter)\n\n### Creating a custom validation\n\nValiktor provides a lot of constraints and validation functions for the most common types, but in some cases this is not enough to meet all needs.\n\nIt's possible to create custom validations in three steps:\n\n#### 1. Define the constraint \n\nTo create a custom constraint, it's necessary to implement the interface `org.valiktor.Constraint`, which has these properties:\n\n* `name`: specifies the name of the constraint, the default value is the class name, e.g.: `Between`.\n* `messageBundle`: specifies the base name of the default message property file, the default value is `org/valiktor/messages`.\n* `messageKey`: specifies the name of the key in the message property file, the default value is the qualified class name plus `message` suffix, e.g.: `org.valiktor.constraints.Between.message`.\n* `messageParams`: specifies a `Map\u003cString, *\u003e` containing the parameters to be replaced in the message, the default values are all class properties, obtained through reflection.\n\nFor example:\n\n```kotlin\ndata class Between\u003cT\u003e(val start: T, val end: T) : Constraint\n```\n\n#### 2. Create the extension function\n\nThe validation logic must be within an extension function of `org.valiktor.Validator\u003cE\u003e.Property\u003cT\u003e`, where `E` represents the object and `T` represents the property to be validated.\n\nThere is an auxiliary function named `validate` that expects a `Constraint` and a validation function as parameters.\n\nFor example:\n\n```kotlin\nfun \u003cE\u003e Validator\u003cE\u003e.Property\u003cInt?\u003e.isBetween(start: Int, end: Int) = \n    this.validate(Between(start, end)) { it == null || it in start.rangeTo(end) }\n```\n\nTo support suspending functions, you must use `coValidate` instead of `validate`:\n\n```kotlin\nsuspend fun \u003cE\u003e Validator\u003cE\u003e.Property\u003cInt?\u003e.isBetween(start: Int, end: Int) = \n    this.coValidate(Between(start, end)) { it == null || it in start.rangeTo(end) }\n```\n\nAnd to use it:\n\n```kotlin\nvalidate(employee) {\n    validate(Employee::age).isBetween(start = 1, end = 99)\n}\n```\n\nNote: null properties are valid (`it == null || ...`), this is the default behavior for all Valiktor functions. If the property is nullable and cannot be null, the function `isNotNull()` should be used.\n\n#### 3. Add the internationalization messages\n\nAdd internationalization support for the custom constraint is very simple. Just add a message to each message bundle file.\n\nFor example:\n\n* `en` (e.g.: `messages_en.properties`):\n\n```\norg.valiktor.constraints.Between.message=Must be between {start} and {end}\n```\n\n* `pt_BR` (e.g.: `messages_pt_BR.properties`):\n\n```\norg.valiktor.constraints.Between.message=Deve estar entre {start} e {end}\n```\n\nNote: the variables `start` and `end` are extracted through the property `messageParams` of the constraint `Between` and will be formatted in the message using the [Message formatters](#message-formatters). If you need a custom formatter, see [Creating a custom formatter](#creating-a-custom-formatter).\n\nSee the [sample](valiktor-samples/valiktor-sample-custom-constraint)\n\n### Coroutines support\n\nValiktor supports suspending functions natively, so you can use it in your validations.\n\nFor example, consider this suspending function:\n\n```kotlin\nsuspend fun countByName(name: String): Int\n```\n\nIt cannot be called by `isValid` because it doesn't allow suspending functions:\n\n```kotlin\nvalidate(employee) {\n    validate(Employee::name).isValid { countByName(it) == 0 } // compilation error\n}\n```\n\nbut we can use `isCoValid`, that expects a suspending function:\n\n```kotlin\nvalidate(employee) {\n    validate(Employee::name).isCoValid { countByName(it) == 0 } // OK\n}\n```\n\n### Validating RESTful APIs\n\nImplementing validation on REST APIs is not always so easy, so developers end up not doing it right. But the fact is that validations are extremely important to maintaining the integrity and consistency of the API, as well as maintaining the responses clear by helping the client identifying and fixing the issues.\n\n#### Spring support\n\nValiktor provides integration with Spring WebMvc and Spring WebFlux (reactive approach) to make validating easier. The module `valiktor-spring` has four exception handlers:\n\nSpring WebMvc:\n\n* `ConstraintViolationExceptionHandler`: handles `ConstraintViolationException` from `valiktor-core`.\n* `InvalidFormatExceptionHandler`: handles `InvalidFormatException` from `jackson-databind`.\n* `MissingKotlinParameterExceptionHandler`: handles `MissingKotlinParameterException` from `jackson-module-kotlin`.\n\nSpring WebFlux:\n\n* `ReactiveConstraintViolationExceptionHandler`: handles `ConstraintViolationException` from `valiktor-core`.\n* `ReactiveInvalidFormatExceptionHandler`: handles `InvalidFormatException` from `jackson-databind`.\n* `ReactiveMissingKotlinParameterExceptionHandler`: handles `MissingKotlinParameterException` from `jackson-module-kotlin`.\n\nAll the exception handlers return the status code `422` ([Unprocessable Entity](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422)) with the violated constraints in the following payload format:\n\n```json\n{\n  \"errors\": [\n    {\n      \"property\": \"the invalid property name\",\n      \"value\": \"the invalid value\",\n      \"message\": \"the internationalization message\",\n      \"constraint\": {\n        \"name\": \"the constraint name\",\n        \"params\": [\n          {\n            \"name\": \"the param name\",\n            \"value\": \"the param value\"\n          }\n        ]\n      }\n    }\n  ]\n}\n```\n\nValiktor also use the Spring Locale Resolver to determine the locale that will be used to translate the internationalization messages.\n\nBy default, Spring resolves the locale by getting the HTTP header `Accept-Language`, e.g.: `Accept-Language: en`.\n\n#### Spring WebMvc example\n\nConsider this controller:\n\n```kotlin\n@RestController\n@RequestMapping(\"/employees\")\nclass EmployeeController {\n\n    @PostMapping(consumes = [MediaType.APPLICATION_JSON_VALUE])\n    fun create(@RequestBody employee: Employee): ResponseEntity\u003cVoid\u003e {\n        validate(employee) {\n            validate(Employee::id).isPositive()\n            validate(Employee::name).isNotEmpty()\n        }\n        return ResponseEntity.created(...).build()\n    }\n}\n```\n\nNow, let's make two invalid requests with `cURL`:\n\n* with `Accept-Language: en`:\n\n```bash\ncurl --header \"Accept-Language: en\" \\\n  --header \"Content-Type: application/json\" \\\n  --request POST \\ \n  --data '{\"id\":0,\"name\":\"\"}' \\\n  http://localhost:8080/employees\n```\n\nResponse:\n\n```json\n{\n  \"errors\": [\n    {\n      \"property\": \"id\",\n      \"value\": 0,\n      \"message\": \"Must be greater than 0\",\n      \"constraint\": {\n        \"name\": \"Greater\",\n        \"params\": [\n          {\n            \"name\": \"value\",\n            \"value\": 0\n          }\n        ]\n      }\n    },\n    {\n      \"property\": \"name\",\n      \"value\": \"\",\n      \"message\": \"Must not be empty\",\n      \"constraint\": {\n        \"name\": \"NotEmpty\",\n        \"params\": []\n      }\n    }\n  ]\n}\n```\n\n* with `Accept-Language: pt-BR`:\n\n```bash\ncurl --header \"Accept-Language: pt-BR\" \\\n  --header \"Content-Type: application/json\" \\  \n  --request POST \\ \n  --data '{\"id\":0,\"name\":\"\"}' \\\n  http://localhost:8080/employees\n```\n\nResponse:\n\n```json\n{\n  \"errors\": [\n    {\n      \"property\": \"id\",\n      \"value\": 0,\n      \"message\": \"Deve ser maior que 0\",\n      \"constraint\": {\n        \"name\": \"Greater\",\n        \"params\": [\n          {\n            \"name\": \"value\",\n            \"value\": 0\n          }\n        ]\n      }\n    },\n    {\n      \"property\": \"name\",\n      \"value\": \"\",\n      \"message\": \"Não deve ser vazio\",\n      \"constraint\": {\n        \"name\": \"NotEmpty\",\n        \"params\": []\n      }\n    }\n  ]\n}\n```\n\nSamples: \n\n* [valiktor-sample-spring-boot-1-webmvc](valiktor-samples/valiktor-sample-spring-boot-1-webmvc)\n* [valiktor-sample-spring-boot-2-webmvc](valiktor-samples/valiktor-sample-spring-boot-2-webmvc)\n\n#### Spring WebFlux example\n\nConsider this router using [Kotlin DSL](https://spring.io/blog/2017/08/01/spring-framework-5-kotlin-apis-the-functional-way#functional-routing-with-the-kotlin-dsl-for-spring-webflux):\n\n```kotlin\n@Bean\nfun router() = router {\n    accept(MediaType.APPLICATION_JSON).nest {\n        \"/employees\".nest {\n            POST(\"/\") { req -\u003e\n                req.bodyToMono(Employee::class.java)\n                    .map {\n                        validate(it) {\n                            validate(Employee::id).isPositive()\n                            validate(Employee::name).isNotEmpty()\n                        }\n                    }\n                    .flatMap {\n                        ServerResponse.created(...).build()\n                    }\n            }\n        }\n    }\n}\n```\n\nNow, let's make two invalid requests with `cURL`:\n\n* with `Accept-Language: en`:\n\n```bash\ncurl --header \"Accept-Language: en\" \\\n  --header \"Content-Type: application/json\" \\\n  --request POST \\ \n  --data '{\"id\":0,\"name\":\"\"}' \\\n  http://localhost:8080/employees\n```\n\nResponse:\n\n```json\n{\n  \"errors\": [\n    {\n      \"property\": \"id\",\n      \"value\": 0,\n      \"message\": \"Must be greater than 0\",\n      \"constraint\": {\n        \"name\": \"Greater\",\n        \"params\": [\n          {\n            \"name\": \"value\",\n            \"value\": 0\n          }\n        ]\n      }\n    },\n    {\n      \"property\": \"name\",\n      \"value\": \"\",\n      \"message\": \"Must not be empty\",\n      \"constraint\": {\n        \"name\": \"NotEmpty\",\n        \"params\": []\n      }\n    }\n  ]\n}\n```\n\n* with `Accept-Language: pt-BR`:\n\n```bash\ncurl --header \"Accept-Language: pt-BR\" \\\n  --header \"Content-Type: application/json\" \\  \n  --request POST \\ \n  --data '{\"id\":0,\"name\":\"\"}' \\\n  http://localhost:8080/employees\n```\n\nResponse:\n\n```json\n{\n  \"errors\": [\n    {\n      \"property\": \"id\",\n      \"value\": 0,\n      \"message\": \"Deve ser maior que 0\",\n      \"constraint\": {\n        \"name\": \"Greater\",\n        \"params\": [\n          {\n            \"name\": \"value\",\n            \"value\": 0\n          }\n        ]\n      }\n    },\n    {\n      \"property\": \"name\",\n      \"value\": \"\",\n      \"message\": \"Não deve ser vazio\",\n      \"constraint\": {\n        \"name\": \"NotEmpty\",\n        \"params\": []\n      }\n    }\n  ]\n}\n```\n\nSamples:\n\n* [valiktor-sample-spring-boot-2-webflux](valiktor-samples/valiktor-sample-spring-boot-2-webflux)\n* [valiktor-sample-spring-boot-2-webflux-fn](valiktor-samples/valiktor-sample-spring-boot-2-webflux-fn)\n\n#### Custom Exception Handler\n\nValiktor provides an interface to customize the HTTP response, for example:\n\n```kotlin\ndata class ValidationError(\n    val errors: Map\u003cString, String\u003e\n)\n\n@Component\nclass ValidationExceptionHandler(\n    private val config: ValiktorConfiguration\n) : ValiktorExceptionHandler\u003cValidationError\u003e {\n\n    override fun handle(exception: ConstraintViolationException, locale: Locale) =\n        ValiktorResponse(\n            statusCode = HttpStatus.BAD_REQUEST,\n            headers = HttpHeaders().apply {\n                this.set(\"X-Custom-Header\", \"OK\")\n            },\n            body = ValidationError(\n                errors = exception.constraintViolations\n                    .mapToMessage(baseName = config.baseBundleName, locale = locale)\n                    .map { it.property to it.message }\n                    .toMap()\n            )\n        )\n}\n```\n\nYou can customize status code, headers and payload by implementing the interface `ValiktorExceptionHandler`.\n\n#### Spring Boot support\n\nFor Spring Boot applications, the module `valiktor-spring-boot-starter` provides auto-configuration support for the exception handlers and property support for configuration.\n\nCurrently the following properties can be configured:\n\n| Property                | Description                                         |\n| ------------------------| --------------------------------------------------- |\n| valiktor.baseBundleName | The base bundle name containing the custom messages |\n\nExample with `YAML` format:\n\n```yaml\nvaliktor:\n  base-bundle-name: messages\n```\n\nExample with `Properties` format:\n\n```properties\nvaliktor.baseBundleName=messages\n```\n\n### Test Assertions\n\nValiktor provides a [module](#valiktor-test) to build fluent assertions for validation tests, for example:\n\n```kotlin\nshouldFailValidation\u003cEmployee\u003e {\n    // some code here\n}\n```\n\nThe function `shouldFailValidation` asserts that a block fails with `ConstraintViolationException` being thrown.\n\nIt's possible to verify the constraint violations using a fluent DSL:\n\n```kotlin\nshouldFailValidation\u003cEmployee\u003e {\n    // some code here\n}.verify {\n    expect(Employee::name, \" \", NotBlank)\n    expect(Employee::email, \"john\", Email)\n    expect(Employee::company) {\n        expect(Company::name, \"co\", Size(min = 3, max = 50))\n    }\n}\n```\n\nCollections and arrays are also supported:\n\n```kotlin\nshouldFailValidation\u003cEmployee\u003e {\n    // some code here\n}.verify {\n    expectAll(Employee::dependents) {\n        expectElement {\n            expect(Dependent::name, \" \", NotBlank)\n            expect(Dependent::age, 0, Between(1, 16))\n        }\n        expectElement {\n            expect(Dependent::name, \" \", NotBlank)\n            expect(Dependent::age, 17, Between(1, 16))\n        }\n        expectElement {\n            expect(Dependent::name, \" \", NotBlank)\n            expect(Dependent::age, 18, Between(1, 16))\n        }\n    }\n}\n```\n\n## Modules\n\nThere are a number of modules in Valiktor, here is a quick overview:\n\n### valiktor-core\n\n[![jar](https://img.shields.io/badge/jar-v0.12.0-green.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-core/0.12.0/jar)\n[![javadoc](https://img.shields.io/badge/javadoc-v0.12.0-blue.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-core/0.12.0/javadoc)\n[![sources](https://img.shields.io/badge/sources-v0.12.0-yellow.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-core/0.12.0/sources)\n\nThe main library providing the validation engine, including:\n\n* 40+ validation constraints\n* 200+ validation functions for all standard Kotlin/Java types\n* Internationalization support\n* Default formatters for array, collection, date and number types\n\n### valiktor-javamoney\n\n[![jar](https://img.shields.io/badge/jar-v0.12.0-green.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-javamoney/0.12.0/jar) \n[![javadoc](https://img.shields.io/badge/javadoc-v0.12.0-blue.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-javamoney/0.12.0/javadoc) \n[![sources](https://img.shields.io/badge/sources-v0.12.0-yellow.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-javamoney/0.12.0/sources)\n\nThis module provides support for JavaMoney API types, including: \n\n* Validation constraints and functions for `MonetaryAmount`\n* Default formatter for `MonetaryAmount`\n\n### valiktor-javatime\n\n[![jar](https://img.shields.io/badge/jar-v0.12.0-green.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-javatime/0.12.0/jar)\n[![javadoc](https://img.shields.io/badge/javadoc-v0.12.0-blue.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-javatime/0.12.0/javadoc)\n[![sources](https://img.shields.io/badge/sources-v0.12.0-yellow.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-javatime/0.12.0/sources)\n\nThis module provides support for JavaTime API types, including: \n\n* Validation constraints and functions for `LocalDate`, `LocalDateTime`, `OffsetDateTime` and `ZonedDateTime`\n* Default formatter for all `LocalDate`, `LocalDateTime`, `LocalTime`, `OffsetDateTime`, `OffsetTime` and `ZonedDateTime`\n\n### valiktor-jodamoney\n\n[![jar](https://img.shields.io/badge/jar-v0.12.0-green.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-jodamoney/0.12.0/jar) \n[![javadoc](https://img.shields.io/badge/javadoc-v0.12.0-blue.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-jodamoney/0.12.0/javadoc) \n[![sources](https://img.shields.io/badge/sources-v0.12.0-yellow.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-jodamoney/0.12.0/sources)\n\nThis module provides support for Joda-Money API types, including: \n\n* Validation constraints and functions for `Money` and `BigMoney`\n* Default formatter for `Money` and `BigMoney`\n\n### valiktor-jodatime\n\n[![jar](https://img.shields.io/badge/jar-v0.12.0-green.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-jodatime/0.12.0/jar)\n[![javadoc](https://img.shields.io/badge/javadoc-v0.12.0-blue.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-jodatime/0.12.0/javadoc)\n[![sources](https://img.shields.io/badge/sources-v0.12.0-yellow.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-jodatime/0.12.0/sources)\n\nThis module provides support for Joda-Time API types, including: \n\n* Validation constraints and functions for `LocalDate`, `LocalDateTime` and `DateTime`\n* Default formatter for all `LocalDate`, `LocalDateTime`, `LocalTime` and `DateTime`\n\n### valiktor-spring\n\n[![jar](https://img.shields.io/badge/jar-v0.12.0-green.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-spring/0.12.0/jar)\n[![javadoc](https://img.shields.io/badge/javadoc-v0.12.0-blue.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-spring/0.12.0/javadoc)\n[![sources](https://img.shields.io/badge/sources-v0.12.0-yellow.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-spring/0.12.0/sources)\n\nSpring WebMvc and WebFlux integration, including:\n\n* Configuration class to set a custom base bundle name\n* Exception handler for `ConstraintViolationException` from Valiktor\n* Exception handlers for `InvalidFormatException` and `MissingKotlinParameterException` from Jackson\n\n### valiktor-spring-boot-autoconfigure\n\n[![jar](https://img.shields.io/badge/jar-v0.12.0-green.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-spring-boot-autoconfigure/0.12.0/jar)\n[![javadoc](https://img.shields.io/badge/javadoc-v0.12.0-blue.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-spring-boot-autoconfigure/0.12.0/javadoc)\n[![sources](https://img.shields.io/badge/sources-v0.12.0-yellow.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-spring-boot-autoconfigure/0.12.0/sources)\n\nProvides auto-configuration support for [valiktor-spring](#valiktor-spring), including:\n \n* Configuration class based on properties\n* Spring WebMvc exception handlers\n* Spring WebFlux exception handlers\n\n### valiktor-spring-boot-starter\n\n[![jar](https://img.shields.io/badge/jar-v0.12.0-green.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-spring-boot-starter/0.12.0/jar)\n[![javadoc](https://img.shields.io/badge/javadoc-v0.12.0-blue.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-spring-boot-starter/0.12.0/javadoc)\n[![sources](https://img.shields.io/badge/sources-v0.12.0-yellow.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-spring-boot-starter/0.12.0/sources)\n\nSpring Boot Starter library including the modules [valiktor-spring](#valiktor-spring) and [valiktor-spring-boot-autoconfigure](#valiktor-spring-boot-autoconfigure)\n\n### valiktor-test\n\n[![jar](https://img.shields.io/badge/jar-v0.12.0-green.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-test/0.12.0/jar)\n[![javadoc](https://img.shields.io/badge/javadoc-v0.12.0-blue.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-test/0.12.0/javadoc)\n[![sources](https://img.shields.io/badge/sources-v0.12.0-yellow.svg)](https://search.maven.org/artifact/org.valiktor/valiktor-test/0.12.0/sources)\n\nThis module provides fluent assertions for validation tests\n\n## Samples\n\n* [valiktor-sample-hello-world](valiktor-samples/valiktor-sample-hello-world)\n* [valiktor-sample-nested-properties](valiktor-samples/valiktor-sample-nested-properties)\n* [valiktor-sample-collections](valiktor-samples/valiktor-sample-collections)\n* [valiktor-sample-javamoney](valiktor-samples/valiktor-sample-javamoney)\n* [valiktor-sample-javatime](valiktor-samples/valiktor-sample-javatime)\n* [valiktor-sample-jodamoney](valiktor-samples/valiktor-sample-jodamoney)\n* [valiktor-sample-jodatime](valiktor-samples/valiktor-sample-jodatime)\n* [valiktor-sample-custom-constraint](valiktor-samples/valiktor-sample-custom-constraint)\n* [valiktor-sample-custom-formatter](valiktor-samples/valiktor-sample-custom-formatter)\n* [valiktor-sample-spring-boot-1-webmvc](valiktor-samples/valiktor-sample-spring-boot-1-webmvc)\n* [valiktor-sample-spring-boot-2-webmvc](valiktor-samples/valiktor-sample-spring-boot-2-webmvc)\n* [valiktor-sample-spring-boot-2-webflux](valiktor-samples/valiktor-sample-spring-boot-2-webflux)\n* [valiktor-sample-spring-boot-2-webflux-fn](valiktor-samples/valiktor-sample-spring-boot-2-webflux-fn)\n\n## Changelog\n\nFor latest updates see [CHANGELOG.md](CHANGELOG.md) file.\n\n## Contributing \n\nPlease read [CONTRIBUTING.md](CONTRIBUTING.md) for more details, and the process for submitting pull requests to us.\n\n## License\n\nThis project is licensed under the Apache License, Version 2.0 - see the [LICENSE](LICENSE) file for details.\n","funding_links":[],"categories":["Libraries"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvaliktor%2Fvaliktor","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvaliktor%2Fvaliktor","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvaliktor%2Fvaliktor/lists"}