Skip to content

useForm composable

The useForm<T> composable enables you to build type-safe forms in Vue with full autocompletion support. It works seamlessly with schema validators like Zod, Valibot, or ArkType, allowing you to infer types directly from your validation schema.

Usage

To get started, import and use the components and functions provided by useForm. You'll benefit from autocompletion for the name attribute on Field, FieldArray, and the error-for attribute on Error components.

Initial values types

Defining initialValues in the useForm options or using the :initial-values prop on the Form component ensures complete type safety for your form data.

Basic Example

vue
<script lang="ts" setup>
import { useForm } from './composable/useForm';

type FormData = {
	username: string;
	password: string;
	stay_loggedin: boolean;
}

const {
	Form,
	Field,
	Error,
	reset,
	handleSubmit,
	setError,
} = useForm<FormData>({
	initialValues: {
		stay_loggedin: false,
	},
});

const submit = handleSubmit((data) => {
	console.log('username', data?.username);
	setError('username', 'Username required');
});
</script>
<template>
	<div>
		<Form @submit="submit" v-slot="{ values }">
			<div>
				<Field name="username" />
				<Error error-for="username" />
			</div>
			<div>
				<Field name="password" type="password" />
			</div>
			<div>
				<Field name="stay_loggedin" v-slot="{ field }">
					<input id="loggedin" type="checkbox" v-bind="field" />
					<label for="loggedin">Stay logged in</label>
				</Field>
			</div>
			<button>Send</button>
			<button type="button" @click="reset">Reset</button>
			<pre>{{ values }}</pre>
		</Form>
	</div>
</template>

API Reference

Options

OptionTypeDescription
initialValuesTSet initial values.
schemaStandardSchemaV1<any, T>Schema definition for validations.
namestringName of the form.
preservebooleanPreserve data even though the component is unMounted.
mode'onChange' | 'onSubmit'Validation execution mode.
(default: 'onSubmit')

Components

NameDescription
FormThe form wrapper component.
FieldFor creating input elements.
FieldArrayFor managing arrays of input elements.
ErrorFor displaying field-specific errors.

Methods

FunctionParameterDescription
handleSubmit(cb: (data: T) => void) => voidHandles form submission and provides typed data to the callback.
setError{ name: T, message: string }Sets an error message for a specific field (typed with autocomplete).
setValue{ name: T, value: any }Sets the value for a specific field (typed with autocomplete).
setValuesRecord<T, any>Sets multiple field values at once (typed with autocomplete).
setInitialValuesRecord<T, any>Sets the initial values for the form.
resetvoidResets the form to its initial values.

Variables

NameDescription
isSubmittingIndicates submit state
valuesCurrent form data values