# ostack/KForm > Open-source Kotlin library for developing demanding forms. Documentation for KForm v1.2.1. It is available as: - [llms.txt](https://kform.ostack.tech/llms.txt): an index of documentation pages. - [llms-full.txt](https://kform.ostack.tech/llms-full.txt): the full documentation in a single file. The [Kotlin API reference](https://kform.ostack.tech/api/packages/kform/index.html) (generated by Dokka) is not included in these files. # Docs # Overview KForm is an open-source Kotlin library for developing demanding forms. KForm uses [Kotlin Multiplatform](https://kotlinlang.org/docs/multiplatform.html) to let developers define a form’s structure and validations in code shared between server and client applications. To learn how to use KForm, start with the user guide: [Get started](https://kform.ostack.tech/user-guide/installation/index.md) An LLM-friendly version of this documentation is available at [llms.txt](https://kform.ostack.tech/llms.txt) (or as a single file at [llms-full.txt](https://kform.ostack.tech/llms-full.txt)). ## Features - Define the schema and validations of your form in common (i.e. shared) Kotlin code, where: - Schemas and validations may be defined over tabular data and/or any other type of data. - Custom validations are easy to implement, may execute asynchronous actions, and may depend on any value of the form or even external context. - Manage your form on the client via a [form manager](https://kform.ostack.tech/user-guide/form-manager/index.md), which: - Automatically validates your form, asynchronously, as it is edited. - Caches validation results, only rerunning validations when the value they’re validating or a value they depend on changes, thus performing well on forms with hundreds to thousands of validations. - Supports dirty/touched field states. - Has easy to use bindings available for [React](https://react.dev/) applications. - Validates values of your form on the server via a [form validator](https://kform.ostack.tech/user-guide/form-validator/index.md) which: - Supports running extra server-only validations (e.g. that require database access). - Access values of your form with Unix-style paths via the form manager or validator. ## Show me some code The following example defines the schema and validations of a login form and validates an example form value as one would on the server: Login form example ```kotlin --8 < -- packages / kform / src / commonTest / kotlin / samples / OverviewSamples.kt:login-form packages / kform / src / commonTest / kotlin / samples / OverviewSamples.kt:test-login-form --8 < -- ``` 1. Model of our form, specified in standard Kotlin code. 1. Definition of our form’s schema, instructing KForm on how to manage and validate it. 1. KForm provides built-in validations such as `Required` or `MinLength`, among others, for common validation scenarios. 1. Custom validations can be defined to further validate the form’s data. This validation emits a validation error when the string it is validating doesn’t contain any digits. 1. The [form validator](https://kform.ostack.tech/user-guide/form-validator/index.md) is typically used on the server-side to validate submitted forms. 1. Validations and other KForm features run asynchronously, so they must run within [coroutines](https://kotlinlang.org/docs/coroutines-overview.html). For Java servers, KForm provides wrapper utilities around [completable futures](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html). 1. Paths are used extensively in KForm to point to parts of data within a form. Here, it specifies the location of the validation error. ## Supported targets KForm currently supports the following targets (via Kotlin Multiplatform): - JVM, for server applications. - JavaScript, for client applications. KForm further provides idiomatic JavaScript bindings (with TypeScript definitions) for consuming the library from JavaScript code, as well as a [React library](https://kform.ostack.tech/user-guide/react-integration/index.md) for integration with [React](https://react.dev/). Support for other targets such as Android or iOS is possible but not yet implemented. ## When to use? KForm is being developed with a main use-case in mind: aiding the development of fairly complicated web-based forms containing dozens to hundreds of validations that should be kept in sync between a client (browser) application and a JVM-based server. These forms often contain tabular data which, for some users, may end up containing many thousands of rows which have to be validated without degrading user experience: something that is often difficult to achieve with different form validation libraries. This isn’t to say that KForm won’t fit other use-cases, just that this is the one it mainly caters to. When deciding whether to use KForm, some constraints should be kept in mind: - Due to the usage of Kotlin’s standard library and the dependency on certain Kotlin Multiplatform libraries such as [kotlinx.coroutines](https://github.com/Kotlin/kotlinx.coroutines/) or [kotlinx.serialization](https://github.com/Kotlin/kotlinx.serialization/), the file size of a JavaScript bundle using KForm can be rather large, reaching ~1.2 MB for the rather simple demo in the KForm repository (which does bundle React, but no React component library). - Thanks to Kotlin Multiplatform, the usage of [Gradle](https://gradle.org/) is required, which might make it hard to adopt KForm in projects already using different build tools. - Although not incredibly complicated, the interaction between Kotlin and JavaScript/TypeScript can sometimes be tricky, forcing developers to write “glue code” in Kotlin/JS to make certain objects or functionality more easily accessible from JavaScript. - We currently don’t provide bindings for any UI library other than React (written in JavaScript/TypeScript, as opposed to React code written in Kotlin). With this in mind, there are some scenarios in which you likely don’t want to use KForm: - Your server doesn’t run on the JVM. Even though we provide bindings for use from JavaScript, we currently don’t offer JavaScript bindings for the more server-related parts of the API, such as the [form validator](https://kform.ostack.tech/user-guide/form-validator/index.md), meaning that even with a JavaScript-based server, you will likely have trouble using KForm. - You have a simple form with only a handful of validations and aren’t already using KForm or other Kotlin dependencies in your client application (in which case the incurred increase in bundle size from pulling KForm together with its Kotlin dependencies might not be worth it). ## License KForm is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). # Installation KForm consists of: - A Kotlin Multiplatform core library, published to Maven Central as [`tech.ostack:kform`](https://central.sonatype.com/artifact/tech.ostack/kform). - A Kotlin/JS library providing bindings for usage from JavaScript, published to Maven Central as [`tech.ostack:kform-js-bindings`](https://central.sonatype.com/artifact/tech.ostack/kform-js-bindings) and to npmjs as [`@ostack.tech/kform`](https://www.npmjs.com/package/@ostack.tech/kform). - A React library for using KForm together with React, published to npmjs as [`@ostack.tech/kform-react`](https://www.npmjs.com/package/@ostack.tech/kform-react). - A Kotlin Multiplatform test library offering a set of testing utilities, published to Maven Central as [`tech.ostack:kform-test`](https://central.sonatype.com/artifact/tech.ostack/kform-test). A typical project using KForm contains three modules: - A shared Kotlin Multiplatform module, containing the definition of the form, compiling to both JVM and JavaScript. - The React client module, consuming the shared module’s JavaScript target and using KForm to render and manage the form. - The JVM server module, consuming the shared module’s JVM target and using KForm to validate submitted forms. For the purpose of these docs, let us assume that all three modules are within the same Gradle build with project paths `:shared`, `:react-app`, and `:server`. Add the Maven Central repository to your Gradle build if not already present: settings.gradle.kts ```kotlin dependencyResolutionManagement { repositories { mavenCentral() } } ``` ## Shared/KMP module Add the core dependency to your `:shared` Kotlin Multiplatform project’s `commonMain` dependencies, the test dependency to the `commonTest` dependencies, and the JavaScript bindings to the `jsMain` dependencies. JavaScript compilation should target ES2015 and represent `Long`s as `bigint`s (which currently requires the `-Xes-long-as-bigint` compiler option): shared/build.gradle.kts ```kotlin plugins { kotlin("multiplatform") // … } kotlin { // … jvm { testRuns["test"].executionTask.configure { useJUnitPlatform() } } js { compilerOptions { target = "es2015" freeCompilerArgs.add("-Xes-long-as-bigint") } binaries.library() browser() generateTypeScriptDefinitions() } sourceSets { commonMain.dependencies { api("tech.ostack:kform:1.2.1") // … } commonTest.dependencies { implementation("tech.ostack:kform-test:1.2.1") // … } jsMain.dependencies { implementation("tech.ostack:kform-js-bindings:1.2.1") // … } // … } } ``` For consuming the shared module in your React application, you might want to create a task to pack the compiled JavaScript. The following example uses the [`node-gradle`](https://github.com/node-gradle/gradle-node-plugin) plugin to achieve this: shared/build.gradle.kts ```kotlin plugins { // … id("com.github.node-gradle.node") version "…" } tasks.register("packJsPackage") { group = "build" dependsOn("jsBrowserProductionLibraryDistribution") val libraryDir = "build/dist/js/productionLibrary" npmCommand = listOf("pack", libraryDir, "--pack-destination", "build") inputs.dir(libraryDir) outputs.file("build/your-form-shared-$version.tgz") } ``` Note `your-form` should typically be replaced with the name of your root Gradle project. ## Client/React application module These instructions will be using [Vite](https://vite.dev/) as the build tool for the React application in conjunction with Gradle via [`node-gradle`](https://github.com/node-gradle/gradle-node-plugin). Other frontend bundling tools should work similarly. Configure Gradle to consume the shared module’s JavaScript target and set up tasks to develop and build the React application: react-app/build.gradle.kts ```kotlin plugins { base id("com.github.node-gradle.node") version "…" } val sharedPackage = project(":shared").file("build/your-form-shared-$version.tgz") val npmInstallShared = tasks.register("npmInstallShared") { group = "build" dependsOn(":shared:packJsPackage") npmCommand = listOf("install", "your-form-shared@file:$sharedPackage") inputs.file(sharedPackage) outputs.dir("node_modules/your-form-shared") } tasks.npmInstall { dependsOn(npmInstallShared) } tasks.register("npmRunDev") { group = "development" dependsOn(tasks.npmInstall) npmCommand = listOf("run", "dev") } val npmRunBuild = tasks.register("npmRunBuild") { group = "build" dependsOn(tasks.npmInstall) npmCommand = listOf("run", "build") inputs.dir("src") inputs.file(sharedPackage) inputs.file("index.html") inputs.file("package.json") inputs.file("tsconfig.json") // … inputs.file("vite.config.ts") outputs.dir("dist/") } tasks.assemble { dependsOn(npmRunBuild) } ``` Due to how Kotlin Multiplatform compiles code to JavaScript, consuming multiple Kotlin/JS modules from JavaScript can be a bit tricky. As such, we won’t use the published `@ostack.tech/kform` package from npmjs and instead consume it from the `:shared` module directly. We still install `@ostack.tech/kform` for its type definitions by installing it “renamed” as `@types/ostack.tech__kform`: react-app/package.json ```json { // … "scripts": { "dev": "vite", "build": "tsc -b && vite build" // … }, "dependencies": { "@ostack.tech/kform-react": "^1.2.1", "react": "…", "react-dom": "…" // … }, "devDependencies": { "@types/ostack.tech__kform": "npm:@ostack.tech/kform@^1.2.1", "@types/react": "…", "@types/react-dom": "…", "@vitejs/plugin-react": "…", "typescript": "…", "vite": "…" // … } } ``` To consume `@ostack.tech/kform` from the `:shared` module, we use a Vite alias targetting the `ostack-kform.mjs` file, like so: react-app/vite.config.ts ```typescript import { resolve } from "node:path"; import react from "@vitejs/plugin-react"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [react()], resolve: { alias: { "@ostack.tech/kform": resolve( import.meta.dirname, "node_modules/your-form-shared/ostack-kform.mjs", ), }, }, }); ``` ## Server/JVM module In your server module, add the dependency to your shared KMP module (if exposing the core KForm library by declaring the dependency via `api`): server/build.gradle.kts ```kotlin dependencies { implementation(project(":shared")) // … } ``` If required, you may also add dependencies to KForm’s core and test JVM modules directly: server/build.gradle.kts ```kotlin dependencies { implementation("tech.ostack:kform-jvm:1.2.1") testImplementation("tech.ostack:kform-test-jvm:1.2.1") // … } ``` You can add a task to copy the built React application to the server’s resources. E.g. for a Spring Boot application: server/build.gradle.kts ```kotlin val copyBuiltReactApp = tasks.register("copyBuiltReactApp") { from(tasks.getByPath(":react-app:npmRunBuild")) into("build/resources/main/static") } tasks.processResources { dependsOn(copyBuiltReactApp) } ``` # Model & schemas How does one represent a form in KForm? Let’s take a look at an example. Imagine that you want to build a form that allows users to purchase bus tickets. A possible model for this form might look like the following: Model of a form for purchasing bus tickets ```kotlin @JsExport data class BusTripForm( var email: String = "", var passengers: Table = tableOf(), ) @JsExport data class Passenger(var name: String = "", var age: Int? = null) ``` As we can see, this form is represented by standard Kotlin classes with mutable properties which, apart from the `Table` data type (explained below) are not at all related to KForm. Given this, how can KForm reason about these seemingly arbitrary types of data? This is what schemas are for: they offer KForm insight on the structure and types of your data. Schemas define the structure of your form and its validations: they provide the means for KForm to create, manipulate, and validate values of your form. The following example shows how the schema of our bus ticket purchasing form can be defined (for now without any validations): Schema of a form for purchasing bus tickets ```kotlin @JsExport val BusTripFormSchema = ClassSchema { BusTripForm::email { StringSchema() } BusTripForm::passengers { TableSchema { ClassSchema { Passenger::name { StringSchema() } Passenger::age { NullableSchema { IntSchema() } } } } } } ``` This definition enables KForm to understand that our form is represented by a class `BusTripForm` containing two fields: `email` and `passengers`, of types `String` and `Table` respectively. As you might notice, a form’s schema usually has a one-to-one correspondence with its model. Note [`@JsExport`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.js/-js-export/) is used on declarations that will be used from the JavaScript client. This includes the root schema and, optionally, classes that are part of the form’s model. ## Supported data types KForm natively supports many of Kotlin’s standard data types: - Classes: via [`ClassSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-class-schema/index.html), as shown above. - `Boolean`, `Byte`, `Char`, `Short`, `Int`, `Long`, `Float`, `Double`, and `String`: via [`BooleanSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-boolean-schema/index.html), [`ByteSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-byte-schema/index.html), [`CharSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-char-schema/index.html), [`ShortSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-short-schema/index.html), [`IntSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-int-schema/index.html), [`LongSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-long-schema/index.html), [`FloatSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-float-schema/index.html), [`DoubleSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-double-schema/index.html), and [`StringSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-string-schema/index.html) respectively. - Nullable data types: via [`NullableSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-nullable-schema/index.html). E.g. the type `Int?` can be represented as `NullableSchema { IntSchema() }`. - Enum classes: via [`EnumSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-enum-schema/index.html). E.g.: ```kotlin @JsExport enum class Gender { MALE, FEMALE, } val GenderSchema = EnumSchema() ``` - `Any?`: via [`AnySchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-any-schema/index.html). Rarely used, but useful when wanting the form to hold some data that KForm doesn’t need to know the type of. The following collections are currently supported: - [`Table`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.datatypes/-table/index.html): via [`TableSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-table-schema/index.html). Tables are KForm’s recommended data structure for representing collections since they provide stable identifiers for each element. E.g. the type `Table` can be represented as `TableSchema { IntSchema() }`. - [`List`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.collections/-list/): via [`ListSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-list-schema/index.html). E.g. the type `List` can be represented as `ListSchema { IntSchema() }`. For temporal-related data types, KForm supports: - [`Instant`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.time/-instant/): via [`InstantSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-instant-schema/index.html). - [kotlinx-datetime](https://github.com/Kotlin/kotlinx-datetime)’s [`LocalDate`](https://kotlinlang.org/api/kotlinx-datetime/kotlinx-datetime/kotlinx.datetime/-local-date/) and [`LocalDateTime`](https://kotlinlang.org/api/kotlinx-datetime/kotlinx-datetime/kotlinx.datetime/-local-date-time/): via [`LocalDateSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-local-date-schema/index.html) and [`LocalDateTimeSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-local-date-time-schema/index.html) respectively. Big numbers are supported via [`kt-math`](https://github.com/gciatto/kt-math/): - [`BigInteger`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.datatypes/-big-integer/index.html) and [`BigDecimal`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.datatypes/-big-decimal/index.html): via [`BigIntegerSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-big-integer-schema/index.html) and [`BigDecimalSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-big-decimal-schema/index.html). Files are supported via KForm’s own `File` datatype: - [`File`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.datatypes/-file/index.html): via [`FileSchema`](https://kform.ostack.tech/api/packages/kform/tech.ostack.kform.schemas/-file-schema/index.html). This datatype is used by KForm to represent files to be uploaded in a form. ## How to model your form When creating the model of your form, you might wonder which data types to use. Should your field be typed as `String` or `String?`, `Int` or `Int?`? What data type should be used for collections? Here are some guidelines: - The preferred data types often depend on what controls will be used to display/edit the form in your UI. For example, it is often better to represent a text field (e.g. ``) as a `String` rather than `String?`, otherwise there would be two possible representations for an “empty” text box: `null` and `""`. If, however, there’s a limited set of possible values for the field, and the form control becomes a ``) should typically be nullable, otherwise there won’t be a reasonable value for representing empty fields. - The previous rules allude to the following, which is worth mentioning: validation requirements don’t always dictate the data type that should be used. I.e. just because a field is mandatory, it doesn’t mean that it should be typed as non-nullable. It is more important to consider whether your data types are able to represent all possible states of your UI form controls. Instead, it might make sense to denote certain characteristics of your form values as validations rather than constraining the data type itself. For more information on validations, see [Validations](https://kform.ostack.tech/user-guide/validations/index.md). - For collections over complex data, prefer `Table` over `List`, e.g. when modeling a table where rows can be added and removed, as shown in the previous `BusTripForm` example. Tables provide stable identifiers for each element, which means that [paths](https://kform.ostack.tech/user-guide/paths/index.md) to elements in the table remain stable even if the table is modified. - Use `List`, e.g. `List`, for small collections of primitive types (e.g. when modeling a checkbox group or a ``, so that values are written to the form manager as the user interacts with the form control, and vice versa: ```typescript const controller = useInput(path, options?); ``` It accepts all options accepted by [`useController`](#usecontroller), as well as the following properties: - `setFormattedValue(formattedValue, state, element)`: Function used to set the formatted value in the form control. The passed value results from calling `format` on the form manager value. If `format` is not defined, then the form manager value is passed directly. By default, this function is capable of setting the values of ``, `